替换 MongoDB 数组中的嵌入文档
有没有一种简单的方法来替换数组中的整个嵌入文档? 假设将:替换
{
"_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"
}
Is there an easy way to replace an entire embedded document in an array?
Say replacing:
{
"_id" : "2",
"name" : "name2",
"xyz..." : "xyz2..."
}
with:
{
"_id" : "2",
"name" : "name6",
"xyz..." : "xyz5..."
"morefields..." : "fields..."
}
Searching for _id (embedded). Or do I need to replace each field individually using $set?
{
"_id" : "2",
"users" : [{
"_id" : "1",
"name" : "name1",
"xyz..." : "xyz1..."
}, {
"_id" : "2",
"name" : "name2",
"xyz..." : "xyz2..."
}],
"name" : "main name"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用“对象数组”模式。您可以使用位置运算符,它应该看起来像这样:
根据我的经验,如果对象具有自然 ID,则“对象数组”模式不是最佳的。在您的情况下,这可以建模如下:
在这种情况下,您可以使用 点符号轻松更新您想要的项目。
You are using the "array of objects" pattern. You can use the positional operator, it should look something like this:
In my experience, the "array of objects" pattern is not optimal if the objects have a natural ID. In your case, this could be modeled as the following:
In this case you can use the dot notation to easily update the item you want.