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']
答案 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" ] }