gpt4 book ai didi

mongodb - 替换 MongoDB 中数组中的嵌入文档

转载 作者:IT老高 更新时间:2023-10-28 13:11:36 26 4
gpt4 key购买 nike

有没有一种简单的方法可以替换数组中的整个嵌入文档?说替换:

{
"_id" : "2",
"name" : "name2",
"xyz..." : "xyz2..."
}

与:

{
"_id" : "2",
"name" : "name6",
"xyz..." : "xyz5..."
"morefields..." : "fields..."
}

正在搜索 _id(嵌入式)。还是我需要使用 $set 单独替换每个字段?

{
"_id" : "2",
"users" : [{
"_id" : "1",
"name" : "name1",
"xyz..." : "xyz1..."
}, {
"_id" : "2",
"name" : "name2",
"xyz..." : "xyz2..."
}],
"name" : "main name"
}

最佳答案

您正在使用“对象数组”模式。您可以使用 positional operator ,它应该看起来像这样:

coll.update( {'_id':'2', 'users._id':'2'}, {$set:{'users.$':{ "_id":2,"name":"name6",... }}}, false, true)

根据我的经验,如果对象具有自然 ID,则“对象数组”模式不是最佳的。在您的情况下,这可以建模如下:

{
"_id" : "2",
"users" :
{ "1" : { "name" : "name1", "xyz..." : "xyz1..." },
"2" : { "name" : "name2", "xyz..." : "xyz2..." }
}
"name" : "main name"
}

在这种情况下,您可以使用 dot notation轻松更新您想要的项目。

var newValue = {  "name" : "name6", "xyz..." : "xyz5...", "morefields..." : "fields..." };
coll.update({_id: 2}, { $set: { "users.2" : newValue } });

关于mongodb - 替换 MongoDB 中数组中的嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9200399/

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