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

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

本文关键字:对象 搜索 数组 字段 文档 操作 findAndModify      更新时间:2023-09-26

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

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

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

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

  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,因为这指的是外部数组。

还要注意,在nodejs下,.findAndModify()的MongoDB驱动程序语法与shell语法非常不同。"查询"answers"更新"部分是单独的参数,而不是shell使用的文档形式,

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

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