Mongo查询中的精确匹配数组

时间:2015-03-28 01:29:57

标签: c# linq mongodb

使用Linq语法,您如何精确匹配文档中的数组?

此查询效果很好,只是它与其他有年龄不是3或4岁的儿童的文档相匹配。

    var query = collection.AsQueryable<Parent>().Where(p => p.Children.Any(c => c.Age == 3) && p.Children.Any(c => c.Age == 4));

例如,它不应该返回此文档:

{
    "_id" : ObjectId("5514c620923a9b55e22f0adf"),
    "Name" : "Bob",
    "Children" : [ 
        {
            "Name" : "Kid1",
            "Age" : 5
        }, 
        {
            "Name" : "Kid2",
            "Age" : 4
        }, 
        {
            "Name" : "Kid3",
            "Age" : 3
        }
    ]
}

并且应该与此文档相符:

{
    "_id" : ObjectId("5514c620923a9b55e22f0adf"),
    "Name" : "Bob",
    "Children" : [ 
        {
            "Name" : "Kid2",
            "Age" : 4
        }, 
        {
            "Name" : "Kid3",
            "Age" : 3
        }
    ]
}

这基本上是这个问题的重复,但使用linq c#语法。

  

Matching an array field which contains any combination of the provided array in MongoDB

如果您还可以使用c#QueryBuilder而不是linq来显示奖励积分。

1 个答案:

答案 0 :(得分:0)

您可以创建另一个数组,其中包含一个不同的年龄列表。即:

{
  ages: [3,4],
  children: [
    { name: "A", age: 3 },
    { name: "A", age: 4 },
    { name: "A", age: 3 }
  ]
}

现在,您可以使用$all查询:http://docs.mongodb.org/manual/reference/operator/query/all/

结合$size查询:http://docs.mongodb.org/manual/reference/operator/query/size/

{ ages: { $all: [3,4], $size: 2 } }