【问题标题】:MongoDB C# driver, query by an array element using regexMongoDB C# 驱动程序,使用正则表达式通过数组元素查询
【发布时间】: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.*"))

【问题讨论】:

  • 你的最终查询对我来说看起来不错,顺便说一句!

标签: c# mongodb linq


【解决方案1】:

我现在正在使用以下内容:

builder.AnyEq("parent.children.name", new BsonRegularExpression(".*ob.*"))

【讨论】:

    【解决方案2】:

    无法在这台机器上测试 C#。如果这不起作用,请告诉我:

    var filter = Builders<People>.Filter.ElemMatch(x => x.Parent.Children, x => Regex.IsMatch(x.Name, "regex"));
    var res = await collection.Find(filter).ToListAsync();
    

    顺便说一句,您可能会喜欢以下技巧:

    // Take your inputted `find` query string:
    string bsonQuery = "{'parent.children': { $elemMatch: { 'name': { $regex: '.*ob.*', $options: 'im' } }}}";
    
    // Use it as the filter!
    var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bsonQuery);
    
    // Results:
    var result = col.FindSync (filter).ToList();
    

    【讨论】:

    • 在您的示例中,您使用类(强类型)。我所拥有的只是“路径”的虚线符号。你能改进你的例子吗?
    • @Antipod 查找 COPO。使用 C# 进行查询时,它们会让您的生活更轻松
    • 感谢您的更新。我几乎可以肯定提供的更新会起作用。问题是:它是一个字符串,我不想构造字符串,我们在驱动程序中有我们可以使用的方法,驱动程序将为我们构造查询,毕竟:)谈到 POCO,我 100% 同意你,但我有一个要求 - JSON 没有定义的结构,它是动态的。
    • 虽然 JSON 是动态的,但 C# 中的一流对象却不是。因此,即使数据可能发生变化,也可以按用途编写 COPO,这对于在其上运行的 C# 代码来说是有意义的。
    • 感谢您的意见。不幸的是,POCO 在我的问题中是一个题外话,对此感到抱歉:) 顺便说一句,我已经更新了问题。
    【解决方案3】:

    我已在家中的数据库上测试了您当前的表达式 (builder.AnyEq("parent.children.name", new BsonRegularExpression(".*ob.*")),但我认为它的行为与您的预期不同。

    Although the c# documentation doesn't explicitly state this,mongoDB 支持对数组字段使用 Regex 过滤器。我已经在 C# 中测试了以下表达式,并且尽管该字段是一个数组,但 Regex 的结果是正确的。

    builder.Regex(MONGO_FIELD_NAME, new BsonRegularExpression("SOME REGEX"));
    

    此外,我在 [online mongo webshel​​l for query arrays] (https://docs.mongodb.com/manual/tutorial/query-arrays/) 中的玩具示例中测试了 Regex。查询db.inventory.find({tags : {$regex : "^bl"}} 将返回带有“空白”或“蓝色”的结果,尽管“标签”字段是一个数组。

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 2016-05-21
      • 2011-11-05
      • 2019-04-08
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多