3

我有一个带有一组字段 f1、f2、f3 的数据库,其中 f3 是一个数组。我想做这样的更新操作

db.collection.update ({f1:1},{$push:{f3:{$each:[ f2's value ],$slice:-2}}})

我在互联网上搜索并没有找到任何东西。我不确定这是否可能。任何帮助将非常感激。

例子:

这是我的一组文件:

doc1 = { name: "User1", score: "Good",  History of scores: ["Good", "Bad", "Average", "Bad"] }
doc2 = { name: "User2", score: "Bad",  History of scores: ["Good", "Average", "Average", "Bad"] }
doc3 = { name: "User3", score: "Good",  History of scores: ["Good", "Good", "Average", "Good"] }

现在假设我们必须插入相应的数据:

{name : "User1", score: "Good"}

我希望该文档更新 user1 的分数历史记录,以便 doc1 变为如下:

doc1 = { name: "User1", score: "Good", History of scores: ["Bad", "Average", "Bad", "Good"] }

另一个相同的更新应该将 doc1 更改为:

doc1 = { name: "User1", score: "Good", History of scores: ["Average", "Bad", "Good", "Good"] }

我希望现在我的问题变得更清楚了。谢谢。

4

2 回答 2

2

尝试这个:

> db.c.find()
{ "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "User1", "score" : "Good", "scores" : [ "Good", "Bad", "Average", "Bad" ] }
> db.c.update({}, {$push: {scores:{$each:['111', '222'], '$slice': -4}}})
> db.c.find()
{ "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "User1", "score" : "Good", "scores" : [ "Average", "Bad", "111", "222" ] }

顺便说一句,我对这种更新有一个问题:如果新对象的大小比以前的大,它会导致将此对象移动到磁盘上的另一个位置(例如,您按下“平均”并弹出“坏”)。“就地”更新更快,您可以在第一次插入时为对象预分配空间,如下所示:

> db.c.insert({ "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "<big_tmp_string>", "score" : "<big_tmp_string>", "scores" : [ "<big_tmp_string>", "<big_tmp_string>", "<big_tmp_string>", "<big_tmp_string>" ] })
> db.c.update({ "_id" : ObjectId("51c156d25a334e9347b576a7")}, {<your_real_obj>}
于 2013-06-19T07:07:49.987 回答
1

现在更新命令可以包含从 MongoDB 4.2 开始的管道,这样的事情可能的。

db.collection.updateOne({ f1: 1 }, [{
  $set: {
    historyOfScores: {
      $concatArrays: [
        "$historyOfScores",
        ["$score"]
      ]
    }
  }
}, {
  $set: {
    score: 'Good'
  }
}]

于 2021-07-23T19:51:37.177 回答