MongoDB - how to request a nested element inside a collection?

I have some data that look 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 thought that such a query would give the advertiser ID:

 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 request did not work. Any idea how I can add fields inside nested elements to the list of fields I want to get?

Thank!

+52
mongodb
Jun 04 2018-12-12T00:
source share
3 answers

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(); 

Link: Retrieving a Subset of Fields and Point Notation

+87
Jun 04 2018-12-12T00:
source share
 db.agencies.find( { "advertisers.created_at" : {$gte : start , $lt : end} } , { program_ids : 1 , advertisers.name : 1 } ).limit(1).pretty(); 
+2
Oct. 15 '13 at 5:56 on
source share

There is one thing called dot notation that MongoDB provides, which allows you to look inside arrays of elements. Using it is as simple as adding a point for each array that you want to enter.

In your case

  "_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" : "", }, { ... } 

If you want to enter the advertisers array to search for the created_at property inside each of them, you can simply write the query using the {' advertisers.created_at : query} property as follows

 db.agencies.find( { 'advertisers.created_at' : { {$gte : start , $lt : end} ... } 
+1
Oct 12 '14 at 15:47
source share



All Articles