如何在mongoDB中投影字段?

inv*_*bl3 5 mongodb mongodb-query aggregation-framework

我的集合中的文档结构如下:

{
  "_id" : ObjectId("569190cd24de1e0ce2dfcd62"),
  "title" : "Star Trek II: The Wrath of Khan",
  "year" : 1982,
  "rated" : "PG",
  "released" : ISODate("1982-06-04T04:00:00Z"),
  "runtime" : 113,
  "countries" : [
    "USA"
  ],
  "awards" : {
    "wins" : 2,
    "nominations" : 9,
    "text" : "2 wins & 9 nominations."
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用投影并添加几个附加参数来获取特定字段的内容。我想采用以下键:titleyearrated以及awards指定的值。(并_id删除)

我这样写是db.movieDetails.find( {}, {title: 1, year: 2013, rated: "PG-13", _id: 0, "awards.wins": 1 }).pretty()为了获取带有值的字段,但控制台显示不同的参数:

{
   "title" : "Star Trek II: The Wrath of Khan",
   "year" : 1982,
   "rated" : "PG",
   "awards" : {
     "wins" : 2,
   }
}
Run Code Online (Sandbox Code Playgroud)

我想要这样的输出,例如:

{
   "title" : "Star Trek II: The Wrath of Khan",
   "year" : 2013,
   "rated" : "PG-13",
   "awards" : {
     "wins" : 0
   }
}
Run Code Online (Sandbox Code Playgroud)

请告诉我,查询中需要更正哪些内容才能只有我的具体要求......我感谢大家的帮助。

Ash*_*shh 5

你可以做类似的事情

db.collection.aggregate([
  {
    $project: {
      title: 1,
      _id: 0,
      year: 2013,
      rated: "PG-13",
      "awards.wins": "0"
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

将给出以下输出

[
  {
    "awards": {
      "wins": "0"
    },
    "rated": "PG-13",
    "title": "Star Trek II: The Wrath of Khan",
    "year": 1982
  }
]
Run Code Online (Sandbox Code Playgroud)