【问题标题】:Mongodb update array with another fieldMongodb用另一个字段更新数组
【发布时间】:2013-06-14 00:05:00
【问题描述】:

我有一个包含一组字段 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"] }

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

【问题讨论】:

  • 加个例子就好了
  • @artech 谢谢。我添加了一个示例。

标签: arrays mongodb field updates


【解决方案1】:

试试这个:

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

【讨论】:

  • @arrtech 谢谢。然而,在本例中,值“111”和“222”是已知的,并在每次请求查询时由用户手动插入。我希望的功能是获取另一个字段中包含的值“111”和“222”,比如“分数”,这样就不需要手动将这些值插入到查询中。关于新对象大小的指针是一个非常新的东西并且非常有用的信息。谢谢。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多