如何在MongoDB中投影字段?

5
我可以帮您进行翻译。这段内容是关于文档集合结构的描述,大致意思如下:

我的文档集合结构如下:

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

我正在尝试使用投影并添加一些额外参数来获取特定字段的内容。我想要获取这些键的值:titleyearratedawards(并删除_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,
   }
}

我想要像这样的输出,例如:
{
   "title" : "Star Trek II: The Wrath of Khan",
   "year" : 2013,
   "rated" : "PG-13",
   "awards" : {
     "wins" : 0
   }
}

告诉我,如何修改查询以满足我的具体要求...感谢大家的帮助。
2个回答

4
你可以这样做。
db.collection.aggregate([
  {
    $project: {
      title: 1,
      _id: 0,
      year: 2013,
      rated: "PG-13",
      "awards.wins": "0"
    }
  }
])

会得到以下输出。
[
  {
    "awards": {
      "wins": "0"
    },
    "rated": "PG-13",
    "title": "Star Trek II: The Wrath of Khan",
    "year": 1982
  }
]

感谢您的解决方案,但我遇到了错误:db.movieDetails.aggregate([ {$project: { title:1, _id:0, year: 2013, rated: "PG-13", "awards.wins": 0 } } ]) assert: command failed: { "ok" : 0, "errmsg" : "Bad projection specification, cannot exclude fields other than '_id' in an inclusion projection: { title: 1.0, _id: 0.0, year: 2013.0, rated: \"PG-13\", awards.wins: 0.0 }", "code" : 40178, "codeName" : "Location40178" } : aggregate failed - invzbl3
@invzbl3,您可以在此处查看:https://mongoplayground.net/p/qr0RiU7CgWX - Ashh
非常感谢,问题解决了!这正是我所需要的。您的网站和解决方案非常有帮助 :) - invzbl3

2
应在find()函数的第一个参数内完成筛选操作,应在find()函数的第二个参数内完成投影操作。

你能举个例子吗? - invzbl3
db.collection.find({year : 2013},{title: 1, year:1 , rated: 1, _id: 0,awards:1, "awards.wins": 1 }) - Serdar
据我理解,您想通过评级和年份字段进行筛选。那么您可以尝试这样做:db.collection.find({year : 2013,rated:"PG-13"},{title: 1, year:1 , rated: 1, _id: 0,awards:1, "awards.wins": 1 })。 - Serdar
谢谢,Serdar。我明白它是如何工作的。db.movieDetails.find({year : 2013, rated:"PG-13", "awards.wins": 0},{title: 1, year:1 , rated: 1, _id: 0,awards:1, "awards.wins": 1 }).pretty() - invzbl3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接