mongodb query by sub-field

2019-04-18 17:58发布

问题:

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}
}

回答1:

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



回答2:

Use dot notation:

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


回答3:

For Exact match on Subdocument

    db.bios.find(
   {
     '_id.module': 'B'
   }
)

the query uses dot notation to access fields in a subdocument:

Refference link