MongoDB:在C#驱动程序中构建查询

Kam*_*rey 5 .net c# mongodb mongodb-.net-driver

我堆积在C#驱动程序中构建这个Mongodb查询:

{ 
    Location: { "$within": { "$center": [ [1, 1], 5 ] } },
    Properties: {
        $all: [
            { $elemMatch: { Type: 1, Value: "a" } },
            { $elemMatch: { Type: 2, Value: "b" } }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步:

var geoQuery = Query.WithinCircle("Location", x, y, radius);
var propertiesQuery = **?**;
var query = Query.And(geoQuery, propertiesQuery);
Run Code Online (Sandbox Code Playgroud)

加成:

上面的查询来自我的另一个问题: MongoDB:匹配多个数组元素 欢迎您参与其解决方案.

Wir*_*rie 5

以下是您希望获得该确切查询的方法:

// 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)
    });
Run Code Online (Sandbox Code Playgroud)

鬼鬼祟祟的部分是,尽管各种Query方法的许多参数都需要BsonValues而不是查询,但您可以通过执行以下操作BsonValueQuery实例创建实例:

// very cool/handy that this works
var bv = BsonValue.Create(Query.EQ("Type", 1)); 
Run Code Online (Sandbox Code Playgroud)

发送的实际查询完全符合您的原始请求:

query = {
  "Properties": {
    "$all": [ 
        { "$elemMatch": { "Type": 1, "Value": "a" }}, 
        { "$elemMatch": { "Type": 2, "Value": "b" }}
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

(我从来没有见过这种$all使用方式,但显然,它听起来还没有记录.)