Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - how to query for a nested item inside a collection?

Tags:

mongodb

I have some data that looks like this:

[     {         "_id" : ObjectId("4e2f2af16f1e7e4c2000000a"),         "advertisers" : [             {                 "created_at" : ISODate("2011-07-26T21:02:19Z"),                 "category" : "Infinity Pro Spin Air Brush",                 "updated_at" : ISODate("2011-07-26T21:02:19Z"),                 "lowered_name" : "conair",                 "twitter_name" : "",                 "facebook_page_url" : "",                 "website_url" : "",                 "user_ids" : [ ],                 "blog_url" : "",             }, 

and I was thinking that a query like this would give the id of the advertiser:

var start  = new Date(2011, 1, 1); > var end  = new Date(2011, 12, 12); > db.agencies.find( { "created_at" : {$gte : start , $lt : end} } , { _id : 1 , program_ids : 1 , advertisers { name : 1 }  } ).limit(1).toArray(); 

But my query didn't work. Any idea how I can add the fields inside the nested elements to my list of fields I want to get?

Thanks!

like image 781
Genadinik Avatar asked Jun 04 '12 16:06

Genadinik


People also ask

How do I test multiple conditions in MongoDB?

Find Multiple Conditions Using the $or Operator The or operator in MongoDB is used to select or retrieve only documents that match at least one of the provided phrases. You can also use this operator in a method like a find() , update() , etc., as per the requirements.

How do I query a nested object 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 write an inner query in MongoDB?

To specify a query condition on fields in an embedded/nested document, use dot notation ( "field. nestedField" ). When querying using dot notation, the field and nested field must be inside quotation marks.

How do I search for an object 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. Here is the query to search in an array of objects in MongoDB.


2 Answers

db.agencies.find(  { "advertisers.created_at" : {$gte : start , $lt : end} } ,  { program_ids : 1 , advertisers.name : 1   }  ).limit(1).pretty(); 
like image 34
Mak Ashtekar Avatar answered Nov 10 '22 06:11

Mak Ashtekar


Use dot notation (e.g. advertisers.name) to query and retrieve fields from nested objects:

db.agencies.find({  "advertisers.created_at": {    $gte: start,    $lt: end   }  }, {  _id: 1,   program_ids: 1,   "advertisers.name": 1  } }).limit(1).toArray(); 

Reference: Retrieving a Subset of Fields and Dot Notation

like image 192
lnmx Avatar answered Nov 10 '22 06:11

lnmx