如何在C#中实现MongoDB嵌套$ elemMatch查询

时间:2016-02-19 13:36:43

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

我有以下格式的MongoDB集合。

{
"_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
"Details" : {
    "a" : [
            [ { 
                "DeviceID" : "log0", 
                "DeviceName" : "Dev0"
              },
              { 
                "DeviceID" : "log1", 
                "DeviceName" : "Dev1"
              }
            ],
            [ { 
                "DeviceID" : "Model0", 
                "DeviceName" : "ModelName0"
              },
              { 
                "DeviceID" : "Model1", 
                "DeviceName" : "ModelName1"
              }
            ]
        ]
    }
}

我正在尝试获取数组中DeviceName的所有文档" a"包含一个特定的值,比如" Name0"。但是,使用Mongo查询时,我可以得到所需的结果:

db.test_collection.find({"Details.a":{$elemMatch:{$elemMatch:{DeviceName : /.*Name0.*/}}}});

现在我正在努力在C#中实现上述查询。任何人都可以指导我吗?

到目前为止,我已经尝试了以下代码,但它没有按预期工作

query = Query.And(Query.ElemMatch("Details.a", Query.And(Query.ElemMatch("DeviceName", Query.Matches("DeviceName", new BsonRegularExpression("Name0"))))));

提前致谢

1 个答案:

答案 0 :(得分:5)

嗯,老实说,用C#编写查询有点棘手,但你总是可以玩耍。

var bsonQuery = "{'Details.a':{$elemMatch:{$elemMatch:{DeviceName : /.*Name0.*/}}}}";
var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bsonQuery);

var result = col.FindSync (filter).ToList();

我将一个简单的MongoDB查询反序列化为一个BsonDocument,作为回报,我将FindAsync作为过滤器传递给我。

最后,你会在变量结果中得到理想的结果。

  

注意:我假设已经建立了MongoDB连接,变量col保存了对MongoDB集合的引用。

编辑:请参阅以下链接https://groups.google.com/forum/#!topic/mongodb-csharp/0dcoVlbFR2A。现在,我们确认C#驱动程序不支持无名过滤器,因此不支持使用Buidlers<BsonDocument>.Filter在上面写入上述查询。

长话短说,您只剩下一个选择,就像我在解决方案中提到的那样进行查询。