gpt4 book ai didi

arrays - Mongodb 用另一个字段更新数组

转载 作者:可可西里 更新时间:2023-11-01 10:33:13 26 4
gpt4 key购买 nike

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

关于arrays - Mongodb 用另一个字段更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com