Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining two $elemMatch queries with AND boolean operator in MongoDB

Tags:

mongodb

nosql

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?

like image 894
fstab Avatar asked Apr 24 '14 15:04

fstab


1 Answers

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

?

like image 161
mnemosyn Avatar answered Oct 06 '22 02:10

mnemosyn