Mongodb更新数组与另一个字段

时间:2013-06-17 22:02:06

标签: arrays mongodb field updates

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

  

db.collection.update({f1:1},{$ push:{f3:{$ each:[ f2的值],$ 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"] }

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

2 个答案:

答案 0 :(得分: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" ] }

btw ,我发现这种更新存在问题:如果新对象的大小超过之前的大小,则会导致将此对象移动到磁盘上的其他位置(例如,您推送“平均”并弹出“坏”)。 “就地”更新速度更快,您可以为第一次插入时的对象预分配空间,如下所示:

> 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>}

答案 1 :(得分:1)

现在更新命令可以包含从 MongoDB 4.2 开始的管道,像 this 这样的东西是可能的。

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