【发布时间】:2020-11-14 02:34:38
【问题描述】:
我正在使用 MongoDB C# 驱动程序2.2 版。我的收藏包含“父”对象。每个父对象都有一个子对象数组。每个孩子都有 name 值:
"parent": {
"children":[
{ "name": "Bob", "age": 10},
{ "name": "Alice", "age": 7},
{ "name": "Tobias", "age": 11}
]
}
我需要将以下代码翻译成 C# 语句/LINQ 语法:
db.getCollection('Parents').find({'parent.children': { $elemMatch: { 'name': { $regex: '.*ob.*', $options: 'im' } }}})
我发现有类似的方法
var builder = Builders<BsonDocument>.Filter;
builder.Regex("parent.children.name", new BsonRegularExpression(".*ob.*")); //does not work with array
和
builder.AnyEq("parent.children.name", "ob"); //without regex
但我不明白如何组合它们。请指教。
更新:
我目前正在使用以下内容,如果您知道它不能正常工作的原因,请纠正我:
builder.AnyEq("parent.children.name", new BsonRegularExpression(".*ob.*"))
【问题讨论】:
-
你的最终查询对我来说看起来不错,顺便说一句!