使用 mongo 同时 pull 和 addtoset [英] Pull and addtoset at the same time with mongo

查看:12
本文介绍了使用 mongo 同时 pull 和 addtoset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,其中的元素可以简化为:

I have a collection which elements can be simplified to this:

{tags : [1, 5, 8]}

数组中至少有一个元素,并且所有元素都应该不同.我想用一个标签替换另一个标签,我认为不会有问题.所以我想出了以下查询:

where there would be at least one element in array and all of them should be different. I want to substitute one tag for another and I thought that there would not be a problem. So I came up with the following query:

db.colll.update({
  tags : 1
},{
  $pull: { tags: 1 },
  $addToSet: { tags: 2 }
}, {
  multi: true
})

很酷,所以它会找到所有带有我不需要的标签的元素 (1),删除它并添加另一个 (2)(如果它已经不存在).问题是我收到一个错误:

Cool, so it will find all elements which has a tag that I do not need (1), remove it and add another (2) if it is not there already. The problem is that I get an error:

不能同时更新‘标签’和‘标签’"

"Cannot update 'tags' and 'tags' at the same time"

这基本上意味着我不能同时执行 pull 和 addtoset.有没有其他方法可以做到这一点?

Which basically means that I can not do pull and addtoset at the same time. Is there any other way I can do this?

当然我可以记住元素的所有 ID,然后删除标记并添加单独的查询,但这听起来不太好.

Of course I can memorize all the IDs of the elements and then remove tag and add in separate queries, but this does not sound nice.

推荐答案

这个错误几乎就是这个意思,因为你不能在同一个更新操作中对同一路径"的两个事物采取行动.您使用的两个运算符并不像您想象的那样按顺序处理.

The error is pretty much what it means as you cannot act on two things of the same "path" in the same update operation. The two operators you are using do not process sequentially as you might think they do.

您可以像使用 批量"操作 API 或其他形式的批量"更新.当然在合理范围内,也可以反过来:

You can do this with as "sequential" as you can possibly get with the "bulk" operations API or other form of "bulk" update though. Within reason of course, and also in reverse:

var bulk = db.coll.initializeOrderedBulkOp();
bulk.find({ "tags": 1 }).updateOne({ "$addToSet": { "tags":  2 } });
bulk.find({ "tags": 1 }).updateOne({ "$pull": { "tags": 1 } });

bulk.execute();

不能保证没有其他东西会尝试修改,但它与您目前获得的一样接近.

Not a guarantee that nothing else will try to modify,but it is as close as you will currently get.

另见原始 "update" 命令多个文件.

这篇关于使用 mongo 同时 pull 和 addtoset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆