5

我堆叠在 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);

添加:

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

4

2 回答 2

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)
    });

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

// 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使用方式,但显然,这听起来好像还没有记录。)

于 2013-03-14T18:53:05.617 回答
3

虽然我可以确认您发布的查询在我的机器上有效,但文档$all似乎表明它不应该接受表达式或查询,而只接受值:

Syntax: { field: { $all: [ <value> , <value1> ... ] }

<expression>(如果允许查询,则文档使用,比较$and)。因此,C# 驱动程序只接受一个数组BsonValue而不是IMongoQuery.

但是,以下查询应该是等效的:

{
    $and: [
        { "Location": { "$within": { "$center": [ [1, 1], 5 ] } } },
        { "Properties" : { $elemMatch: { "Type": 1, "Value": "a" } } },
        { "Properties" : { $elemMatch: { "Type": 2, "Value": "b" } } }   
    ]
}

转换为 C# 驱动程序为

var query = 
Query.And(Query.WithinCircle("Location", centerX, centerY, radius),
Query.ElemMatch("Properties", Query.And(Query.EQ("Type", 1), Query.EQ("Value", "a"))),
Query.ElemMatch("Properties", Query.And(Query.EQ("Type", 2), Query.EQ("Value", "b"))));
于 2013-03-14T18:22:24.840 回答