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

Mongodb query documents where nested array is equal or subset of fixed array

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

想法是 return 嵌套数组相等或固定数组的子集的所有文档。示例:

固定数组:["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# 驱动程序解决方案,请 post 无论如何请在这里。会有帮助。

非常感谢!!!

在聚合中使用 mongo Set Operator using $setIsSubset 你会得到你的结果,检查以下查询:

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()

尝试

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

解释:

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

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