Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb query by sub-field

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} } 
like image 231
Linlin Avatar asked Mar 26 '13 08:03

Linlin


People also ask

How do I query a nested field in MongoDB?

MongoDB Nested Query Match on a Nested Field You can use the dot notation (“field. nestedField”) to specify query criteria for fields in embedded/nested documents. For queries that use dot notation, fields and nested fields must be enclosed in double-quotes.

How do I access nested objects in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


2 Answers

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

like image 61
AdaTheDev Avatar answered Sep 23 '22 08:09

AdaTheDev


Use dot notation:

db.XXX.find({ "_id.module" : "B" }) 
like image 22
shx2 Avatar answered Sep 26 '22 08:09

shx2