0

I have a mongo collection where each document look something like this:

{
  title: "blah blah",
  stuff: [
    {
      id:"001",
      data:"blah blah blah"
    },
    {
      id:"002",
      data:"bleeh blah blooh"
    },
    {
      id:"003",
      data:"bow wow wow"
    }
  ]
}

I want to find all documents where the 'stuff' array contains at least one object where 'id' is '001'.

My initial attempt was this:

db.mycollection.find({ stuff: [ { id: "001" } ] });

But evidently this is not correct.

What is the correct query?

  • 1
    Use [dot notation](https://docs.mongodb.com/manual/core/document/#dot-notation). Something like `db.mycollection.find({ "stuff.id": "001" });` – s7vr Jun 21 '17 at 16:17
  • @Veeram You should post that as an answer, it'll get an upvote from me. – Vince Bowdren Jun 21 '17 at 17:02

1 Answers1

0

Use the $elemMatch operator

db.mycollection.find( { stuff: { $elemMatch: { id: "001"} } } )

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

Mark Unsworth
  • 3,027
  • 2
  • 20
  • 21
  • 1
    Just fyi. [Single query condition](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#single-query-condition) don't require the use of `$elemMatch`. – s7vr Jun 21 '17 at 16:46