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

Javascript FindModify,如何对文档进行操作';s数组搜索对象并更改字段值,javascript,mongodb,mongodb-query,Javascript,Mongodb,Mongodb Query,我试图在文档的数组中找到一个对象,并更新其字段 db.rescuemodels.findAndModify({ query: { "features": { $elemMatch: { "properties.title": "W" } } }, update: { $set: { "features": {

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

db.rescuemodels.findAndModify({
    query: {
        "features": {
            $elemMatch: {
                "properties.title": "W"
            }
        }
    },
    update: {
        $set: {
            "features": {
                "properties": {
                    "title": "XXX"
                }
            }
        }
    }
})
查询很好,结果是一个匹配元素,但在本例中如何使更新方法仅更改一个字段
title
?因为现在它创建了新数组或对象,并清除了旧数组。

MongoDB为此提供了一个操作符,以及一个用于引用数组中匹配元素的操作符:

  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" }] },

    ]
}
位置匹配在那里不起作用,因为您无法执行
功能。$.properties.$.name
和匹配的元素索引将是
0
,而不是
1
,因为这是指外部数组

还请注意,在nodejs下,的MongoDB驱动程序语法与shell语法完全不同。“查询”和“更新”部分是独立的参数,而不是shell使用的文档形式,

MongoDB为此目的提供了引用数组匹配元素的运算符:

  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" }] },

    ]
}
位置匹配在那里不起作用,因为您无法执行
功能。$.properties.$.name
和匹配的元素索引将是
0
,而不是
1
,因为这是指外部数组


还请注意,在nodejs下,的MongoDB驱动程序语法与shell语法完全不同。“查询”和“更新”部分是独立的参数,而不是shell所使用的文档表单。

要更新数组“功能”中的单个元素,可以使用位置运算符$。您的查询将如下所示

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

要更新数组“features”中的单个元素,可以使用位置运算符$。您的查询将如下所示

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

您是否尝试过$set:{“features.properties.title”:“XXX”}我很惊讶其他查看此内容的人都没有注意到这是关于更新数组的。您是否尝试过$set:{“features.properties.title”:“XXX”}我很惊讶其他查看此内容的人都没有注意到这是关于更新数组的。