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

findAndModify, How to make operations on document's array search objects and change fields values

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

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

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

MongoDB 有 "Dot Notation" for this purpose, as well as the positional $ 运算符用于引用数组的匹配元素:

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

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

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

如果您正在嵌套数组,则 MongoDB 无法仅在 "positional operator beyond the "outer" 数组中匹配:

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

    ]
}

位置匹配在那里不起作用,因为你不能做 features.$.properties.$.name 并且匹配的元素索引将是 0 而不是 1 因为它指的是外部数组。

另请注意,在 nodejs 下,.findAndModify() 的 MongoDB 驱动程序语法与 shell 语法完全不同。 "query" 和 "update" 部分是单独的参数,而不是 shell、

使用的文档形式

要更新数组中的单个元素 "features",您可以使用位置运算符 $。您的查询看起来像这样...

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