3

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

styvane
  • 59,869
  • 19
  • 150
  • 156
FuriousGeorge
  • 4,561
  • 5
  • 29
  • 52

1 Answers1

9

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" ] }    
DaveStSomeWhere
  • 2,475
  • 2
  • 22
  • 19
  • That double negative is so bizarre, but like you said, it works. I wonder what the performance is on it? – FuriousGeorge Mar 03 '15 at 02:11
  • Do you have any idea how I could modify this so that if `x` contained an array of arrays (i.e. [ ['A', 'B'] ]) instead of just an array of elements? I'd like to unroll the array of arrays and match individual elements like before and not have to match arrays. – FuriousGeorge Mar 03 '15 at 16:25
  • Is there a way to write the above query in Spring Data JPA ? – Shameera Anuranga Sep 02 '21 at 12:46