嵌套数组相等的Mongodb查询文档或固定数组的子集

时间:2015-06-16 18:37:44

标签: c# arrays mongodb subset mongodb-.net-driver

我一直在试图解决以下问题(我正在使用新的c#2.0驱动程序)撞墙:

这个想法是返回嵌套数组相等的所有文档或固定数组的子集。例如:

固定数组:[“A”,“B”,“C”]

容器文档:

{
    container1 { Name: "name1", Tags: [ "A", "B" ] },
    container2 { Name: "name4", Tags: [ "A", "B", "C", "D" ] },
    container3 { Name: "name2", Tags: [ "A" ] },
    container4 { Name: "name3", Tags: [ "A", "B", "C" ] }
}

根据以上数据,结果应为:

{
    container1 { Name: "name1", Tags: [ "A", "B" ] },
    container3 { Name: "name2", Tags: [ "A" ] },
    container4 { Name: "name3", Tags: [ "A", "B", "C" ] }
}

注意container2不是结果集的一部分 [“A”,“B”,“C”,“D”]不是子集,也不等于[“A”,“B”,“C”]

如果您有非2.0-C#-driver解决方案,请在此处发布。它会有所帮助。

非常感谢!!!

2 个答案:

答案 0 :(得分:1)

在聚合中使用mongo Set Operator进行聚合,您将获得结果,请查看以下查询:

db.collectionName.aggregate({
  "$project": {
    "Name": 1,
    "Tags": 1,
    "match": {
      "$setIsSubset": ["$Tags", ["A", "B", "C"]] //check Tags is subset of given array in your case array is ["A","B","C"]
    }
  }
}, {
  "$match": {
    "match": true // return only those matched true values
  }
}, {
  "$project": {
    "Name": 1,
    "Tags": 1
  }
}).pretty()

答案 1 :(得分:0)

尝试

db.collectionName.find({$or:[{Tags: ["A","B","C"]},{Tags: {$in:["A","B","C"], $not : {$all : ["A","B","C"]}}}]})

<强>解释

$ in给出包含给定集合中至少一个元素的所有文档; $ all给出给定集合的超集,包括集合本身。

您想要找到的是给定的集合包含至少一个元素但不包含其他元素的任何集合