FuriousGeorge
FuriousGeorge

Reputation: 4681

$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].

Upvotes: 4

Views: 2238

Answers (2)

ElyashivLavi
ElyashivLavi

Reputation: 1811

Note: In newer Mongo DB Version you can use it as filter with "$expr" syntax:

{$expr: {
    $setIsSubset: [ "$myArray",[0,1]]
}}

Will return true if myArray field contains [0], [1] or [0,1]

Upvotes: 0

DaveStSomeWhere
DaveStSomeWhere

Reputation: 2540

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" ] }    

Upvotes: 10

Related Questions