如何在 C# 中实现 MongoDB 嵌套 $elemMatch 查询
How to implement MongoDB nested $elemMatch Query in C#
我有一个 MongoDB 集合,格式如下。
{
"_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
"Details" : {
"a" : [
[ {
"DeviceID" : "log0",
"DeviceName" : "Dev0"
},
{
"DeviceID" : "log1",
"DeviceName" : "Dev1"
}
],
[ {
"DeviceID" : "Model0",
"DeviceName" : "ModelName0"
},
{
"DeviceID" : "Model1",
"DeviceName" : "ModelName1"
}
]
]
}
}
我正在尝试获取数组 "a" 中 DeviceName
包含特定值的所有文档,比如 "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"))))));
提前致谢
老实说,用 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,在 return 我将其作为过滤器传递给 FindAsync。
最终,您将在可变结果中获得期望的结果。
Note: I'm assuming MongoDB connection has been established and variable col
holds reference to MongoDB collection.
编辑:请参阅以下 link https://groups.google.com/forum/#!topic/mongodb-csharp/0dcoVlbFR2A。现在已确认 C# 驱动程序不支持无名过滤器,因此目前不支持使用 Buidlers<BsonDocument>.Filter
编写上述查询。
长话短说,你只有一个选择,那就是按照我上面在我的解决方案中提到的方式进行查询。
我有一个 MongoDB 集合,格式如下。
{
"_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
"Details" : {
"a" : [
[ {
"DeviceID" : "log0",
"DeviceName" : "Dev0"
},
{
"DeviceID" : "log1",
"DeviceName" : "Dev1"
}
],
[ {
"DeviceID" : "Model0",
"DeviceName" : "ModelName0"
},
{
"DeviceID" : "Model1",
"DeviceName" : "ModelName1"
}
]
]
}
}
我正在尝试获取数组 "a" 中 DeviceName
包含特定值的所有文档,比如 "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"))))));
提前致谢
老实说,用 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,在 return 我将其作为过滤器传递给 FindAsync。
最终,您将在可变结果中获得期望的结果。
Note: I'm assuming MongoDB connection has been established and variable
col
holds reference to MongoDB collection.
编辑:请参阅以下 link https://groups.google.com/forum/#!topic/mongodb-csharp/0dcoVlbFR2A。现在已确认 C# 驱动程序不支持无名过滤器,因此目前不支持使用 Buidlers<BsonDocument>.Filter
编写上述查询。
长话短说,你只有一个选择,那就是按照我上面在我的解决方案中提到的方式进行查询。