如果您想获取确切的查询结果,以下是操作步骤:
// create the $elemMatch with Type and Value
// as we're just trying to make an expression here,
// we'll use $elemMatch as the property name
var qType1 = Query.EQ("$elemMatch",
BsonValue.Create(Query.And(Query.EQ("Type", 1),
Query.EQ("Value", "a"))));
// again
var qType2 = Query.EQ("$elemMatch",
BsonValue.Create(Query.And(Query.EQ("Type", 2),
Query.EQ("Value", "b"))));
// then, put it all together, with $all connection the two queries
// for the Properties field
var query = Query.All("Properties",
new List<BsonValue> {
BsonValue.Create(qType1),
BsonValue.Create(qType2)
});
这里的诡计在于,虽然各种Query
方法的许多参数都期望BsonValue
而不是查询条件,但你可以通过执行以下操作从Query
实例创建一个BsonValue
实例:
// very cool/handy that this works
var bv = BsonValue.Create(Query.EQ("Type", 1))
实际发送的查询与您最初的请求完全匹配:
query = {
"Properties": {
"$all": [
{ "$elemMatch": { "Type": 1, "Value": "a" }},
{ "$elemMatch": { "Type": 2, "Value": "b" }}
]
}
}
我之前也从未见过这种$all
用法,但显然,它听起来像尚未记录。