2

文档:

order1.filter = ['tag1','tag2']
order2.filter = ['tag1','tag2','tag3']

想要得到:

query ['tag1','tag2'] -> (only order1)
query ['tag1','tag2','tag3'] -> (order1 and order2)
query ['tag1','tag2','tag3','tag4', etc ] -> (order1 and order2)

and

query ['tag1','tag3'] -> (null)
query ['tag2','tag3'] -> (null)

所有值order.filter都应该在查询数组中

怎么做?尝试过的指令 $all, $in :(

4

1 回答 1

0

您可以使用聚合框架来做到这一点(我所知道的常规发现无法做到这一点)。

我认为这基本上是重复的,因此为您的字段调整该代码会得到类似的结果:

//sample documents:
> db.docs.find({},{_id:0})
{ "order" : 1, "filter" : [ "t1", "t2" ] }
{ "order" : 2, "filter" : [ "t1", "t2", "t3" ] }
var tagArray = [ "t1", "t2" ];   // array to "match"
db.docs.aggregate( [
    {
        "$project" : {
            "order" : 1,
            "filter" : 1,
            "killFlag" : {
                "$const" : [
                    true,
                    false
                ]
            }
        }
    },
    {
        "$unwind" : "$filter"
    },
    {
        "$unwind" : "$killFlag"
    },
    {
        "$match" : {
            "$nor" : [
                {
                    "filter" : {
                        "$in" : tagArray
                    },
                    "killFlag" : true
                }
            ]
        }
    },
    {
        "$group" : {
            "_id" : "$order",
            "filter" : {
                "$addToSet" : "$filter"
            },
            "killFlag" : {
                "$max" : "$killFlag"
            }
        }
    },
    {
        "$match" : {
            "killFlag" : false
        }
    },
    {
        "$project" : {
            "_id" : 1,
            "filter" : 1
        }
    }
]);
于 2013-05-29T16:09:05.230 回答