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

前端 未结 3 1080
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 15:22

I have some data that looks like this:

[
    {
        \"_id\" : ObjectId(\"4e2f2af16f1e7e4c2000000a\"),
        \"advertisers\" : [
            {
                   


        
相关标签:
3条回答
  • 2020-11-27 15:42

    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

    0 讨论(0)
  • 2020-11-27 15:45

    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} ... }
    
    0 讨论(0)
  • 2020-11-27 15:59
    db.agencies.find( 
    { "advertisers.created_at" : {$gte : start , $lt : end} } , 
    { program_ids : 1 , advertisers.name : 1   } 
    ).limit(1).pretty();
    
    0 讨论(0)
提交回复
热议问题