combining two $elemMatch queries with AND boolean operator in MongoDB

mongodb, nosql

Solution

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

?

Problem

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?

Original source

Related problems