mongodb query by sub-field

Linlin picture Linlin · Mar 26, 2013 · Viewed 24.4k times · Source

How to query all {"module" : "B"} ?

The following query doesn't work:

db.XXX.find({ "_id" : { "module" : "B" } });

Thanks a ton!

There data looks like:

{
  "_id" : {"module" : "A","date" : ISODate("2013-03-18T07:00:00Z")},
  "value" : {"count" : 1.0}
}

{
  "_id" : {"module" : "B","date" : ISODate("2013-03-18T08:00:00Z")},
  "value" : {"count" : 2.0}
}

Answer

AdaTheDev picture AdaTheDev · Mar 26, 2013

Try:

db.XXX.find({ "_id.module" :  "B" });

The difference is your original query would be trying to match on that entire subdocument (i.e. where _id is a subdocument containing a "module" field with value "B" and nothing else)

Reference: MongoDB Dot Notation