MongoDB-查找具有数组组合的任何文档

时间:2018-12-20 16:46:27

标签: arrays mongodb

mongo文档如下:

{
    _id: '',
    names: ['ab', 'bc']
}
{
    _id: '',
    names: ['ab', 'de', 'fg']
}
{
    _id: '',
    names: ['bc']
}
{
    _id: '',
    names: ['ab', 'bc', 'cd']
}

我有一个输入数组:

['ab', 'bc', 'cd']

问题:如何获取所有文件,其中“名称”等于输入数组的任意组合?

结果:“ names”为以下任何一个的所有文档都应返回

['ab']
['bc']
['cd']
['ab', 'bc']
['bc', 'ab']
['bc', 'cd']
['cd', 'bc']
... and so on..
['ab', 'bc', 'cd']

1 个答案:

答案 0 :(得分:0)

您可以在$expr中使用find来获取$size中的$setIntersection,其名称数组为

db.tt.find({$expr : {$gt : [{$size : {$setIntersection : ["$names", ["ab","bc","cd"]]}}, 0]}})

样品采集

> db.tt.find()
{ "_id" : "1", "names" : [ "ab", "bc" ] }
{ "_id" : "2", "names" : [ "ab", "de", "fg" ] }
{ "_id" : "3", "names" : [ "bc" ] }
{ "_id" : "4", "names" : [ "ab", "bc", "cd" ] }

带有$expr$setIntersection

> db.tt.find({$expr : {$gt : [{$size : {$setIntersection : ["$names", ["ab","bc","cd"]]}}, 0]}})
{ "_id" : "1", "names" : [ "ab", "bc" ] }
{ "_id" : "2", "names" : [ "ab", "de", "fg" ] }
{ "_id" : "3", "names" : [ "bc" ] }
{ "_id" : "4", "names" : [ "ab", "bc", "cd" ] }

带有$in(如安东尼的评论所述)

> db.tt.find({names : {$in : ["ab","bc","cd"]}})
{ "_id" : "1", "names" : [ "ab", "bc" ] }
{ "_id" : "2", "names" : [ "ab", "de", "fg" ] }
{ "_id" : "3", "names" : [ "bc" ] }
{ "_id" : "4", "names" : [ "ab", "bc", "cd" ] }