findAndModify,如何对文档的数组搜索对象进行操作并更改字段值 [英] findAndModify, How to make operations on document's array search objects and change fields values
问题描述
我尝试在文档数组中找到一个对象,并更新其字段.
I try to find one object in document's array, and update its fields.
db.rescuemodels.findAndModify({
query: {
"features": {
$elemMatch: {
"properties.title": "W"
}
}
},
update: {
$set: {
"features": {
"properties": {
"title": "XXX"
}
}
}
}
})
查询很好,结果是一个匹配元素,但是在此示例title
中,如何使更新方法仅更改一个字段?因为现在它会创建新的数组或对象并清理旧的数组.
Query is fine, result is one matching element, but how to make update method change just one field in this example title
? Because now it create new array or object and clean old array.
推荐答案
MongoDB具有点符号" ,以及位置$
运算符,用于引用数组的匹配元素:
MongoDB has "Dot Notation" for this purpose, as well as the positional $
operator for referencing matched elements of an array:
db.rescuemodels.findAndModify({
"query": { "features.properties.title":"W" },
"update": { "$set": { "features.$.properties.title":"XXX" } }
})
请注意,这仅在存在单个数组时才有效,如:
Note that this only works when there is a single array present as in:
{
"features": [
{ "properties": { "name": "A" } },
{ "properties": { "name": "W" } }
}
}
如果要嵌套数组,则MongoDB不能仅在位置"运算符之外的外部"数组中进行匹配:
If you are nesting arrays then MongoDB cannot match in "positional operator beyond the "outer" array only:
{
"features": [
{ "properties": [{ "name": "A" }, { "name": "W" }] },
]
}
在那里不能进行位置匹配,因为您不能执行features.$.properties.$.name
,并且匹配的元素索引将是0
而不是1
,因为它是指外部数组.
Postional matching will not work there because you cannot do features.$.properties.$.name
and the matched element index would be 0
and not 1
as this refers to the outer array.
Also note that under nodejs the MongoDB driver syntax for .findAndModify()
is quite different to the shell syntax. The "query" and "update" parts are separate arguments there rather than the document form as used by the shell,
这篇关于findAndModify,如何对文档的数组搜索对象进行操作并更改字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!