有人熟悉mongodb的 $[<identifier>] 操作吗
发布于 6 年前 作者 lovegnep 2299 次浏览 来自 问答

假设文档如下:

	{
		 _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 回复

我能想到分两步操作 : 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}})

@CRAZYFAKE 谢谢。可是这样就不是原子性了。

来自酷炫的 CNodeMD

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

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

@vendar 感谢

来自酷炫的 CNodeMD

回到顶部