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!
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.
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.
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.
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.
db.agencies.find( { "advertisers.created_at" : {$gte : start , $lt : end} } , { program_ids : 1 , advertisers.name : 1 } ).limit(1).pretty();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With