如何在MongoDB中使用更新来移动数据?

时间:2019-01-26 20:27:29

标签: mongodb

假设我有一个文档...

{
        "_id" : ObjectId("5c4cc127c33477ec8841d317"),
        "review_date" : "2019-01-26T04:07:43.345Z",
        "comment" : "decent product",
        "score" : 4,
        "reviewer_id" : "barry"
}

我想将其更新为...

{
        "_id" : ObjectId("5c4cc127c33477ec8841d317"),
        "review_date" : "2019-01-26T05:15:13.122Z",
        "comment" : "awesome product",
        "score" : 5,
        "reviewer_id" : "barry",
        "history" : [
                {
                        "review_date" : "2019-01-26T04:07:43.345Z",
                        "comment" : "decent product",
                        "score" : 4
                }
        ]
}

我将如何更改?

换句话说,将某些字段移动/复制到文档的其他区域,然后用新值替换某些现有字段。目的是将更改历史记录以数组的形式存储在同一文档中-可能会有很多审阅更改。

1 个答案:

答案 0 :(得分:1)

您打算做的是添加历史记录。您可以通过在已设置$ set的情况下使用db.collection.findOneAndUpdate来实现此目的。

一个具有集合名称product的示例为:

db.products.findOneAndUpdate({ _id: ObjectId("5c4cc127c33477ec8841d317") }, {
  $set: {
    score: 5,
    history: [{
               "review_date" : "2019-01-26T04:07:43.345Z",
               "comment" : "decent product",
               "score" : 4
   }]
  }
})
相关问题