之前我們介紹了如何更新文檔,并簡單的介紹了更新文檔時可以使用選項進行指定當更新內(nèi)容不存在時,可以進行新增文檔。具體可以參考:
MongoDB 更新文檔(更新一條文檔)https://blog.csdn.net/m1729339749/article/details/129983304
最近遇到了一個需求,文檔中包含了一個數(shù)組對象,需要篩選數(shù)組對象中滿足條件的元素進行更新。
一、準備數(shù)據(jù)
向批次中新增兩個批次的商品數(shù)據(jù)
db.batch.insertMany([
{ "_id": 1, "foods": [
{ "name": "蘋果", "total": "20" },
{ "name": "可口可樂", "total": "30" },
{ "name": "北京方便面", "total": "10" }
]
},
{ "_id": 2, "foods": [
{ "name": "伊利純牛奶", "total": "5" },
{ "name": "可口可樂", "total": "20" },
{ "name": "營養(yǎng)快線", "total": "20" }
]
},
]);
二、arrayFilters
語法:
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2.1
}
)
其中arrayFilters用于過濾數(shù)組對象中的元素。
例子:找到營養(yǎng)快線的數(shù)量為20的元素,并將數(shù)量更新為30
(1)查詢營養(yǎng)快線的數(shù)量為20的文檔
db.batch.find(
{
"foods.name": "營養(yǎng)快線",
"foods.total": "20"
}
)
查詢的結(jié)果如下:
{
"_id" : 2,
"foods" : [
{
"name" : "伊利純牛奶",
"total" : "5"
},
{
"name" : "可口可樂",
"total" : "20"
},
{
"name" : "營養(yǎng)快線",
"total" : "20"
}
]
}
(2)對營養(yǎng)快線的數(shù)量進行修改
db.batch.updateOne(
{
"foods.name": "營養(yǎng)快線",
"foods.total": "20"
},
{
"$set": { "foods.$[element].total": "30" }
},
{
"arrayFilters": [
{
"element.name": "營養(yǎng)快線",
"element.total": "20"
}
]
}
)
其中,
arrayFilters:代表的是對數(shù)組中的元素進行過濾,找到滿足條件的數(shù)組中的元素后執(zhí)行更新操作。
$[element]:代表的是過濾定位符,用于定位每一條數(shù)組元素。
執(zhí)行完操作后,數(shù)組中的元素會被修改,修改后的文檔如下:文章來源:http://www.zghlxwxcb.cn/news/detail-647353.html
{
"_id" : 1,
"foods" : [
{
"name" : "蘋果",
"total" : "20"
},
{
"name" : "可口可樂",
"total" : "30"
},
{
"name" : "北京方便面",
"total" : "10"
}
]
}
{
"_id" : 2,
"foods" : [
{
"name" : "伊利純牛奶",
"total" : "5"
},
{
"name" : "可口可樂",
"total" : "20"
},
{
"name" : "營養(yǎng)快線",
"total" : "30"
}
]
}
從文檔中可以看出,營養(yǎng)快線的數(shù)量被修改成了30文章來源地址http://www.zghlxwxcb.cn/news/detail-647353.html
到了這里,關(guān)于MongoDB 更新文檔(更新數(shù)組對象中的元素)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!