0

with given collection "foo", we have field "bar" that looks like this:

"bar": [{uid:1, mid: 10}, {uid:1, mid: 12}, {uid:2, mid: 14}, {uid:2, mid: 15}, {uid:2, mid: 18}] 

How can I make a query to fetch all "foos" on the field "bar" that satisfies following condition: "uid" = 2 and "mid" in [14, 18]

3
  • you can unwind it. Then, it's easier to make such kind of query. You want to do this query for all collections ? Commented Apr 2, 2015 at 16:02
  • Isn't $unwind used only for aggregation framework? No, I just want to query one collection. Commented Apr 2, 2015 at 16:33
  • you are right, it is used in aggregation. I was thinking in complex way while it can be done so easily. My bad... Commented Apr 2, 2015 at 20:00

1 Answer 1

2

There's two ways to interpret your condition

all "foos" on the field "bar" that satisfies following condition: "uid" = 2 and "mid" in [14, 18]

Do you mean "find all documents in the foo collection such that there is an element e of the bar array satisfying e.uid = 2 and e.mid is an element of [14, 18]"? If so, the MongoDB query, written in the mongo shell, is

db.foo.find({ "bar" : { "$elemMatch" : { "uid" : 2, "mid" : { "$in" : [14, 18] } } } })

Do you mean "find all documents in the foo collection such that there is a bar.uid value of 2 and bar.mid value in [14, 18]"? If so, the MongoDB query, written in the mongo shell, is

db.foo.find({ "bar.uid" : 2, "bar.mid" : { "$in" : [14, 18] } })

The following example demonstrates the differences between these queries:

> db.foo.drop()
> db.foo.insert({ "_id" : 0, "bar" : [{ "uid" : 2, "mid" : 14 }] })
> db.foo.insert({ "_id" : 1, "bar" : [{ "uid" : 2, "mid" : 99 }, { "uid" : 3, "mid" : 18 }] })

// first version
> db.foo.find({ "bar" : { "$elemMatch" : { "uid" : 2, "mid" : { "$in" : [14, 18] } } } })
{ "_id" : 0, "bar" : [{ "uid" : 2, "mid" : 14 }] }

// second version
> db.foo.find({ "bar.uid" : 2, "bar.mid" : { "$in" : [14, 18] } })
{ "_id" : 0, "bar" : [{ "uid" : 2, "mid" : 14 }] }
{ "_id" : 1, "bar" : [{ "uid" : 2, "mid" : 99 }, { "uid" : 3, "mid" : 18 }] }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Close enough. However, "bar.mid" MUST have all members from given expression "$in": [14,18]. I tried with "$all" operator, but nothing happens...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.