我在 C# 驱动程序中构建了这个 Mongodb 查询:
{
Location: { "$within": { "$center": [ [1, 1], 5 ] } },
Properties: {
$all: [
{ $elemMatch: { Type: 1, Value: "a" } },
{ $elemMatch: { Type: 2, Value: "b" } }
]
}
}
接下来的事情:
var geoQuery = Query.WithinCircle("Location", x, y, radius);
var propertiesQuery = **?**;
var query = Query.And(geoQuery, propertiesQuery);
加法:
上述查询取 self 的另一个问题: MongoDB: Match multiple array elements 欢迎您参与其解决方案。
最佳答案
如果您想获得确切的查询,请按以下方法:
// 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
而不是查询,但您可以创建一个 BsonValue
通过执行以下操作从 Query
实例中获取实例:
// 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
用法,但显然,它听起来像 it's just not documented。)
关于c# - MongoDB:在 C# 驱动程序中构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15415850/