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

Mongodb

Mongodb Problem Overview


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!

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 2 - Mongodb

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

Solution 3 - Mongodb

There is one thing called dot notation that MongoDB provides that allows you to look inside arrays of elements. Using it is as simple as adding a dot for each array 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 go inside the array of advertisers to look for the property created_at inside each one of them, you can simply write the query with the property {'advertisers.created_at': query} like follows

db.agencies.find( { 'advertisers.created_at' : { {$gte : start , $lt : end} ... }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGenadinikView Question on Stackoverflow
Solution 1 - MongodblnmxView Answer on Stackoverflow
Solution 2 - MongodbMak AshtekarView Answer on Stackoverflow
Solution 3 - Mongodbuser3611442View Answer on Stackoverflow