mongodb - 如果数组中的一组值在另一个给定数组中则匹配 [with Aggregation]

mongodb - match if a group of values from an array is in another given array [with Aggregation]

我已经找了 3 个小时的解决方案,但我还没有找到它。

我有以下合集:

{text: 'random text 1', indexes:[1,2] },
{text: 'random text 2', indexes:[1,3] },
{text: 'random text 3', indexes:[2,4] },

我只想拥有给定数组中所有索引值的文档,例如 [1,2,4]

使用上面的示例,我希望得到以下输出:

{text: 'random text 1', indexes:[1,2] },
{text: 'random text 3', indexes:[2,4] },

[1,2][1,2,4] -> OK

[1,3] 不在 [1,2,4] 中,因为 3 -> 不正常

[1,4][1,2,4] -> OK

有什么想法吗?感谢您的回答! :)

您可以在这个 $match 阶段使用其中之一:

{
  "$match": {
    "$expr": {
      "$setIsSubset": ["$indexes",[1,2,4]]
    }
  }
}

示例here

  • 使用$elemMatch和双重否定($not$nin):
{
  "$match": {
    "indexes": {
      "$not": {
        "$elemMatch": {
          "$nin": [1,2,4]
        }
      }
    }
  }
}

示例here