MongoDB 更新文档(更新数组对象中的元素)

之前我们介绍了如何更新文档,并简单的介绍了更新文档时可以使用选项进行指定当更新内容不存在时,可以进行新增文档。具体可以参考:

MongoDB 更新文档(更新一条文档)https://blog.csdn.net/m1729339749/article/details/129983304
最近遇到了一个需求,文档中包含了一个数组对象,需要筛选数组对象中满足条件的元素进行更新

一、准备数据

向批次中新增两个批次的商品数据

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": "营养快线", "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用于过滤数组对象中的元素。

例子:找到营养快线的数量为20的元素,并将数量更新为30

(1)查询营养快线的数量为20的文档

db.batch.find(
    { 
        "foods.name": "营养快线", 
        "foods.total": "20" 
    }
)

查询的结果如下:

{
	"_id" : 2,
	"foods" : [
		{
			"name" : "伊利纯牛奶",
			"total" : "5"
		},
		{
			"name" : "可口可乐",
			"total" : "20"
		},
		{
			"name" : "营养快线",
			"total" : "20"
		}
	]
}

(2)对营养快线的数量进行修改

db.batch.updateOne(
    { 
        "foods.name": "营养快线", 
        "foods.total": "20" 
    }, 
    {
        "$set": { "foods.$[element].total": "30" }
    },
    {
        "arrayFilters": [
            { 
                "element.name": "营养快线", 
                "element.total": "20"
            }
        ]
    }
)

其中,

arrayFilters:代表的是对数组中的元素进行过滤,找到满足条件的数组中的元素后执行更新操作。

$[element]:代表的是过滤定位符,用于定位每一条数组元素。

执行完操作后,数组中的元素会被修改,修改后的文档如下:

{
	"_id" : 1,
	"foods" : [
		{
			"name" : "苹果",
			"total" : "20"
		},
		{
			"name" : "可口可乐",
			"total" : "30"
		},
		{
			"name" : "北京方便面",
			"total" : "10"
		}
	]
}
{
	"_id" : 2,
	"foods" : [
		{
			"name" : "伊利纯牛奶",
			"total" : "5"
		},
		{
			"name" : "可口可乐",
			"total" : "20"
		},
		{
			"name" : "营养快线",
			"total" : "30"
		}
	]
}

从文档中可以看出,营养快线的数量被修改成了30

猜你喜欢

转载自blog.csdn.net/m1729339749/article/details/132268979