gpt4 book ai didi

MongoDB 更新插入数组中的子文档并返回更新后的子文档

转载 作者:可可西里 更新时间:2023-11-01 10:19:15 24 4
gpt4 key购买 nike

假设我有这样一个文档:

{ 
"_id" : ObjectId(1234),
"name": "foo",
"bars": [
{ "name": "n1", "myBool": true },
{ "name": "n2", "myBool": false },
{ "name": "n3", "myBool": false }
]
}

我想找到 name(或整个子文档,这并不重要)并将 myBool 更改为 true对于 bars 中的第一个子文档,对于原子操作中给定的 _id 当前为 false。例如,对于上面的数据,我想返回 n2 并将 myBool 设置为 true for n2_id 等于 ObjectId(1234) 的文档。

我怎样才能做到这一点?

最佳答案

运行 findAndModify 参数 new 设置为 true 的命令,因此返回修改后的文档而不是原始文档。

更新应使用 $ positional operator它标识数组中要更新的元素,而无需明确指定元素在数组中的位置。为此,数组字段必须作为查询文档的一部分出现。

输出文档有一个 value 字段,其中包含命令返回的文档:

var result = db.runCommand({
"findAndModify": "collection",
"query": {
"_id" : 1234,
"bars.myBool": false
},
"update": { "$set": { "bars.$.myBool": true } },
"new": true
});
printjson(result.value);

示例输出

{
"_id" : 1234,
"name" : "foo",
"bars" : [
{
"name" : "n1",
"myBool" : true
},
{
"name" : "n2",
"myBool" : true
},
{
"name" : "n3",
"myBool" : false
}
]
}

关于MongoDB 更新插入数组中的子文档并返回更新后的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41039349/

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