Search code examples
mongodbmongodb-query

$setIsSubset for regular queries in Mongo


I am looking to do the equivalent of $setIsSubset http://docs.mongodb.org/manual/reference/operator/aggregation/setIsSubset/ for regular (i.e. NOT aggregate) queries in MongoDB. How can I do this?

Assume that I have the documents

{ 'x' : ['A', 'B'] }
{ 'x' : ['A', 'D'] }

And that

filter = ['A', 'B', C']

I want to do a find({"x" : {'$setIsSubSet':filter}}) and expect only to get back

{ 'x' : ['A', 'B'] }

It seems like most conditional commands match any not all. I also want it to be a subset, so it seems that $and and $all would not match [A,B] to [A,B,C].


Solution

  • You could try the following in the shell:

    var filer = ['A', 'B', 'C']
    db.coll2.find({x: {"$not": {"$elemMatch": {"$nin" : filer }}}})
    

    Output

        { "_id" : ObjectId("54f4d72f1f22d4a529052760"), "x" : [  "A",  "B" ] }