7

I have two distinct mongoDB queries that represent two different conditions, for example:

{ stuff: { $elemMatch: { foo: 1, bar: "a" } } }

and:

{ stuff: { $elemMatch: { foo: 2, bar: "b" } } }

where stuff is an array of elements that have both foo and bar fields set.

Now, I am not sure how to match elements in the collection that meet at the same time the two aforementioned conditions.

Just to be clear: in this case I need to get all elements that have both one element of stuff that has foo set as 1 with bar set as "a" and also one element of stuff that has foo set as 2 with bar set as "b".

Doing { stuff: { $elemMatch: { foo: { $in: [1, 2] }, bar: { $in: ["a", "b"] } } } is wrong, since it will behave like an OR on the two expression (and including two new expressions).

Any idea on how to AND them?

Community
  • 1
  • 1
fstab
  • 4,801
  • 8
  • 34
  • 66
  • not really sure what you want to accomplish. How can `stuff.foo` be equal to `1` and `2` at the same time? That's only possible if `foo` is an array. In that case, this is a duplicate of http://stackoverflow.com/questions/5366687/how-to-check-if-an-array-field-contains-a-unique-value-or-another-array-in-mongo – mnemosyn Apr 24 '14 at 15:07
  • @mnemosyn: hmm, maybe it is. Thanks for the pointer! :) – fstab Apr 24 '14 at 15:09
  • @mnemosyn: so, maybe is it: ``{ stuff: { foo: { $all: [1, 2] } } }`` ? But what if I have another field, like ``bar`` inside elements of ``stuff`` ? (I will update the question) – fstab Apr 24 '14 at 15:11

1 Answers1

8

Just to be clear: in this case I need to get all elements that have both one element of stuff that has foo set as 1 with bar set as "a" and also one element of stuff that has foo set as 2 with bar set as "b".

I hope I got it. Shouldn't that be

db.coll.find({ $and: [ 
                  { "stuff" : { $elemMatch : { "foo" : 1, "bar" : "a" } } },   
                  { "stuff" : { $elemMatch : { "foo" : 2, "bar" : "b" } } } ]});

?

mnemosyn
  • 45,391
  • 6
  • 76
  • 82