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

标签 c# .net mongodb mongodb-.net-driver

我在 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/

相关文章:

mongodb - $exists : true (sparse indexes) 的最佳复合索引

c# - 在函数内设置 Expression<Func<T>> 的值

c# - 在 C# 中根据天数获取月数

c# - Viewbag检查item是否存在并写出html和value错误

.net - 如何映射嵌套类型

c# - HTTP/2 与 ASP.NET Core 2.2

javascript - 如何使用 $in 查询 mongodb 中 id 存储在 `var ids` 数组中的文档?

c# - 想要在嵌入标准 C# 应用程序的 WebBrowser 控件中启用 BHO

c# - 在配置文件中动态注入(inject)基于关闭值的 WCF ServiceContract 的具体实现

mongodb - 按照给定的优先级按两个顺序查找和排序