CNode

有人熟悉mongodb的 $[<identifier>] 操作吗

问答
Llovegnep发布于8 年前最后回复8 年前4 回复3023 浏览0 收藏

假设文档如下:

	{
		 _id:ObjectId("aafdfefef343fdsfs"),
		name:"hehe",
		itemList:[
			{
				itemType:1,
				count:100
			},
			{
				itemType:2,
				count:100
			},
			{
				itemType:3,
				count:100
			},
			{
				itemType:4,
				count:100
			},
			{
				itemType:5,
				count:100
			},				
		]
	}
	

现在要实现将itemList中itempType为1的count减小1, itempType为5的count减小2,要怎么操作呢?

查看回复

回复 (4)

C
CRAZYFAKE#1·8 年前

我能想到分两步操作 : itemList中itempType为1的count减小1 ==>> db.getCollection('test').update({"itemList.itemType":1},{$inc:{"itemList.$.count":-1}}) itempType为5的count减小2 ==>> db.getCollection('test').update({"itemList.itemType":5},{$inc:{"itemList.$.count":-2}})

V
vendar#3·8 年前

可以用Bulk包一下,对同一文档操作是原子性的。

来自✨ Node.js开源项目精选

参与回复
登录后即可参与回复。登录