gpt4 book ai didi

javascript - findAndModify,如何对文档的数组搜索对象进行操作并更改字段值

转载 作者:行者123 更新时间:2023-11-28 13:26:16 25 4
gpt4 key购买 nike

我尝试在文档数组中查找一个对象,并更新其字段。

db.rescuemodels.findAndModify({
query: {
"features": {
$elemMatch: {
"properties.title": "W"
}
}
},
update: {
$set: {
"features": {
"properties": {
"title": "XXX"
}
}
}
}
})

查询没问题,结果是一个匹配元素,但是如何使更新方法仅更改此示例中的一个字段title?因为现在它创建新的数组或对象并清理旧数组。

最佳答案

MongoDB 有 "Dot Notation"为此目的,以及 positional $用于引用数组的匹配元素的运算符:

  db.rescuemodels.findAndModify({
"query": { "features.properties.title":"W" },
"update": { "$set": { "features.$.properties.title":"XXX" } }
})

请注意,这仅在存在单个数组时才有效,如下所示:

{
"features": [
{ "properties": { "name": "A" } },
{ "properties": { "name": "W" } }
}
}

如果您嵌套数组,那么 MongoDB 无法仅在“外部”数组之外的“位置运算符”中进行匹配:

{
"features": [
{ "properties": [{ "name": "A" }, { "name": "W" }] },

]
}

位置匹配在那里不起作用,因为您无法执行 features.$.properties.$.name 并且匹配的元素索引将为 0 而不是 1 因为 this 指的是外部数组。

另请注意,在 Nodejs 下,MongoDB 驱动程序语法为 .findAndModify()与 shell 语法完全不同。 “查询”和“更新”部分是单独的参数,而不是 shell 使用的文档形式,

关于javascript - findAndModify,如何对文档的数组搜索对象进行操作并更改字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28845053/

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