如何更新 MongoDB 中的子文档?

How can I update a subdocument in MongoDB?

在 Mongo 中创建的用于更新子文档的代码无法正常工作。所以我尝试更新 Mongo Shell.
中的子文档 这是文档(位置)和子文档(评论):

{
"_id" : ObjectId("56d8c73314fbc7e702cfb8c4"),
"name" : "Costly",
"address" : "150, Super Street",
"coords" : [
    -0.9630884,
    51.451041
],
"reviews" : [
    {
        "author" : "kyle riggen1",
        "_id" : ObjectId("56d8de74cc7f953efd8455d9"),
        "rating" : 4,
        "timestamp" : ISODate("2015-06-01T06:00:00Z"),
        "reviewText" : "will the ID work?"
    }
],
"rating" : 0,
"__v" : 2

}

以下是我更新子文档的一些尝试:
This question gave this format:

update({ 
       _id: "56d8c73314fbc7e702cfb8c4", 
       "reviews._id": ObjectId("56d8de74cc7f953efd8455d9")
   },{
       $set: {"reviews.$.rating": 1}
   }, false, true
);

这返回了 "update is not defined" 错误,如图所示:

2016-03-03T22:52:44.445-0700 E QUERY    [thread1] ReferenceError: update is not defined :
@(shell):1:1

我认为这是因为命令没有以 db.locations.update()

开头

MongoDB documentation used this format:

db.locations.update(
   {
     _id: "56d8c73314fbc7e702cfb8c4",
     review: { $elemMatch: { author: "kyle riggen1" } }
   },
   { $set: { "location.$.rating" : 1 } }
)

这 returns 一个有效的更新,但更新实际上并没有发生,如图所示:

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

This question used this format:

db.locations.update({
    _id: "56d8c73314fbc7e702cfb8c4",
    'review.author': 'kyle riggen1'
  },
  { $set: { 'review.$.rating': 1 }}
)

此 returns 与 MongoDB 文档相同,如下所示:

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

所以我猜这些查询是有效的,但我的数据没有得到更新。我的数据可能会被索引错误吗?甚至可以通过 Mongoose API 更新实际位置。

您可以通过 $push 或 $addToSet 来完成。

db.col.update(
        { name: 'reviews', 'list.id': 2 }, 
        {$push: {'list.$.items': {id: 5, name: 'item5'}}}
    )

请参阅 mongodb 手册中的参考资料

https://docs.mongodb.org/manual/reference/operator/update/push/

请知悉db.collection.update( criteria, objNew, upsert, multi )

  1. criteria: 匹配条件
  2. objNew: 更新内容
  3. upsert:真还是假
    • true : 如果不存在,则插入它
    • false : 如果不存在,不插入
  4. multi:真还是假
    • true : 更新所有匹配的文档
    • false : 只更新第一个匹配的文档