$addToSet 像 $push 一样工作 [英] $addToSet works like $push

查看:73
本文介绍了$addToSet 像 $push 一样工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现非常典型的 $addToSet 和 $inc 组合,但出于某种奇怪的原因,$addToSet 添加了多个具有相同 ID 的记录(工作方式类似于 $push):

I'm trying to implement quite typical combination of $addToSet and $inc but for some strange reason $addToSet adds multiple records with the same id (works like $push):

{ _id: 52ce27691cb76b5a60cc11f7,
  news: 
   [ { _id: 52ce2769c2f35d3d21000018,
       count: 2,
       item: 52ce2769c2f35d3d21000017 },
     { item: 52ce2769c2f35d3d21000017,
       _id: 52ce2769c2f35d3d21000019 } ] }

代码如下:

        this.update({ _id : interval._id },
            { $addToSet : { news : { item : item } } },
            function (err) {
                if (err) {
                    callback(err);
                    return;
                }

                this.update({ _id : interval._id, 'news.item' : item },
                    { $inc : { 'news.$.count' : 1 } },
                    callback);
            }.bind(this));

这段代码被调用了两次,所以创建了两个项目:52ce2769c2f35d3d21000017.$inc 部分运行良好.iteminterval 是猫鼬模型对象.

This code was called two times so two item: 52ce2769c2f35d3d21000017 was created. $inc part works well. item and interval are mongoose model objects.

推荐答案

来自 $addToSet 的文档:仅当值不在数组中时才将值添加到数组中"

From the documentation of $addToSet: "adds a value to an array only if the value is not in the array already"

但什么是价值"?在本例中,它是整个对象,因为这是您尝试添加到数组中的值.但是,这些对象并不等效,因为您首先添加的对象已经增加了 count,而要添加的对象则没有.因此,它们在所有字段中的值并不相同,MongoDB 不会将它们视为相等".

But what is "the value"? In this case it's the entire object, because that's the value that you're trying to add to the array. However, the objects aren't equivalent because the one you've added first already has an increased count, while the to-be-added object does not. Hence, they don't have the same value in all fields and MongoDB doesn't regard them as being 'equal'.

请记住,_id 不是嵌入数组中的特殊字段,也没有其他语义.

Keep in mind that _id is not a special field in an embedded array and has no additional semantics.

这篇关于$addToSet 像 $push 一样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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