[英]Mongodb update array with another field
我有一个带有一组字段 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"] }
我希望现在我的问题变得更清楚了。 谢谢。
试试这个:
> 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>}
现在,更新命令可以包含输油管线的MongoDB的4.2的,像这是可能的。
db.collection.updateOne({ f1: 1 }, [{
$set: {
historyOfScores: {
$concatArrays: [
"$historyOfScores",
["$score"]
]
}
}
}, {
$set: {
score: 'Good'
}
}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.