如何在嵌入式文档中获取单个字段?

时间:2017-04-27 06:19:32

标签: mongodb

假设我有一个类似以下的文件

{
"_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
    }
]

}

当我运行db.users.find( { favorites: { artist: "Picasso", food: "pizza" } }, { "favorites.food": 1 } ).pretty()

之类的查询时

我得到以下结果

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

是否可以只获得food字段

  

{" food" :"披萨" }

没有favorites键?

1 个答案:

答案 0 :(得分:0)

您可以使用 $project

进行汇总来实现此目的
db.users.aggregate([  
   {  
      $match:{  
         favorites:{  
            artist:"Picasso",
            food:"pizza"
         }
      }
   },
   {  
      $project:{  
         _id:0,
         food:"$favorites.food"
      }
   }
])