我正在尝试使用 C# 在 MongoDB 中使用嵌套数组文档实现文本搜索功能。我有一个以下格式的 MongoDB 集合。
{
"_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
"Customers" : {
"Contact" : [
[
{
"FirstName" : "Swetha",
"LastName" : "DevAnand"
}
]
]
}
}
Mongo 查询:
db.test_collection.find({"Customers.Contact":{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}});
在上面的 MongoDB 查询中,我想使用 C# 对最内层的 BSON 文档数组进行 LIKE 搜索。但是,我在 Mongo 查询中使用嵌套的 $elemMatch 实现了这一点。但是在 C# 中尝试做同样的事情时,它需要每个 ElemMatch 查询的字段名。在上面的例子中,最里面的 Contact 字段数组没有任何显式字段名。到目前为止,我已经尝试了以下所有 C# 代码来实现该方案,但没有任何帮助。
var regex = new BsonRegularExpression(searchVal,"i");
query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("LastName", Query.Matches("LastName", regex)))));
query = Query.And(Query.Matches("Customers.Contact.$.LastName",regex));
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.EQ("LastName", regex)));
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.Matches("LastName", regex)));
query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("$", Query.EQ("LastName", regex)))));
非常感谢任何帮助。
最佳答案
经过一周的奋斗,找到了方法。实现上述 MongoDB 查询的最佳方法是将其反序列化为一个 BsonDocument,后者将作为过滤器传递给 FindAsync。
var bQuery = "{'Customers.Contact':{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}}";
var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bQuery);
var result = collection.FindSync(filter).ToList();
感谢 Saleem 先生。请参阅以下链接了解更多详情。 How to implement MongoDB nested $elemMatch Query in C#
关于c# - 使用 C# 查询 MongoDB 嵌套数组文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35574851/