0

Lets say i have a document like following

{
"_id" : 1,
"name" : "sue",
"age" : 19,
"type" : 1,
"status" : "P",
"favorites" : {
    "artist" : "Picasso",
    "food" : "pizza"
},
"finished" : [
    17,
    3
],
"badges" : [
    "blue",
    "black"
],
"points" : [
    {
        "points" : 85,
        "bonus" : 20
    },
    {
        "points" : 85,
        "bonus" : 10
    }
]

}

when i run query like db.users.find( { favorites: { artist: "Picasso", food: "pizza" } }, { "favorites.food": 1 } ).pretty()

i am getting following result

{ "_id" : 1, "favorites" : { "food" : "pizza" } }

Is it possible to get only food field like

{ "food" : "pizza" }

without favorites key?

Hari
  • 1,545
  • 1
  • 22
  • 45

1 Answers1

0

you can achieve this using aggregation with $project

db.users.aggregate([  
   {  
      $match:{  
         favorites:{  
            artist:"Picasso",
            food:"pizza"
         }
      }
   },
   {  
      $project:{  
         _id:0,
         food:"$favorites.food"
      }
   }
])
felix
  • 9,007
  • 7
  • 41
  • 62
  • i am getting empty document like `{ }` – Hari Apr 27 '17 at 06:39
  • thanks man, can u please tell me diffference between `aggregate` and `find` if possible – Hari Apr 27 '17 at 06:54
  • @N.HariHaraSudhan aggregation is similar to find() but it allows you to achive more complex queries/document reformatting; See [aggregation](https://docs.mongodb.com/manual/aggregation/) for details – felix Apr 27 '17 at 07:04
  • according to your answer i am assuming it takes `$favorites` variable reference for object `favorites` , then it add `food : $favorites.food` as a new field in document, am i right?? – Hari Apr 27 '17 at 09:40