简体   繁体   English

mongodb - 如果数组中的一组值在另一个给定数组中,则匹配[带有聚合]

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

I'm looking for a solution since 3 hours and I don't get it yet.自 3 小时以来,我一直在寻找解决方案,但我还没有得到它。

I have the following collection:我有以下收藏:

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

and I would like to have only the documents that have all the index values in a given array like for example [1,2,4]我只想拥有在给定数组中具有所有索引值的文档,例如[1,2,4]

using the example above, I would like to have the following output:使用上面的示例,我想要以下 output:

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

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

[1,3] is not in [1,2,4] because of 3 -> Not OK [1,3]不在[1,2,4]中,因为 3 ->不行

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

Any idea?任何想法? thanks for your answer: :)感谢您的回答: :)

You can use one of this this $match stage:您可以使用此$match阶段之一:

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

Example here这里的例子

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

Example here这里的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM