我正在使用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)))));
非常感谢您的帮助。