gbro3n
gbro3n

Reputation: 6967

MongoDB - How to find where a document field contains a subdocument with a given name? (Example query and document included)

Here I am trying to retrieve documents where the document contains a document DummyFoo, which in turn contains a document DummyBar?

As far as I can tell my syntax below is correct, but no results are returned, though I know that they exist. Have I structured my query incorrectly?

{ "DummyFoo" : { "$elemMatch" : { "DummyBar": { "$exists" : true } }}}

Below is an example of a document that I would expect to match:

{
  "_id" : ObjectId("5423d66ba077e6205cc9ecef"),
  "Title" : "Test 1234587611",
  "Subtitle" : "Test 1 Subtitle",
  "DummyFoo" : {
    "DummyDate" : "2014-09-25T09:46:35.6626303+01:00",
    "DummyBar" : {
      "Name" : "Test",
      "Number" : 1
    }
  }
}

Upvotes: 1

Views: 2488

Answers (1)

Abhishek Pathak
Abhishek Pathak

Reputation: 1569

$elemMatch is specifically made for querying arrays.In this case, you have a nested json, which mongodb recognises as an embedded document.

You can use the dot notation to query embedded documents.

 { "DummyFoo.DummyBar": { "$exists" : true }}

Upvotes: 3

Related Questions