仅向数组添加唯一性,并在更新时保持字段计数 [英] Add Unique only to array and keep field count on update
问题描述
我将一个项目数组(stringId)存储在集合中.此数组中的所有元素都必须是唯一的.因此,我使用$ addToSet推送项目.
I store in a collection an array of item (stringId). All element in this array must be unique. So I use $addToSet to push my item.
但是,我也想在同一请求中设置字段中数组的大小:
But, I also would like to set in the same request the size of my array in a field :
{
unique_array: ['12', '20', '18'],
size_of_array: 3
}
=>添加到设置15
=> Add to set 15
{
unique_array: ['12', '20', '18', '15'], => Add to set
size_of_array: 4 => Incremented
}
=>添加到设置18
=> Add to set 18
{
unique_array: ['12', '20', '18', '15'], => Already in the set
size_of_array: 4 => Not incremented
}
谢谢!
推荐答案
对于这种类型的操作,您不应使用 $addToSet
当然,由于 $inc
都会发生是否添加到数组(设置").
For this type of operation you should not use $addToSet
since of course the $inc
would happen regardless of whether anything was added to the array ( "set" ) or not.
相反,请使用 $ne
运算符测试阵列在查询中:
Instead, test the arrays with the $ne
operator in the query:
db.collection.update(
{ "unique_array": { "$ne": 18 } }, <-- existing element
{
"$push": { "unique_array": 18 },
"$inc": { "size_of_array": 1 }
}
)
删除数组成员的方法也一样,但是当然这次您测试是否相等:
The same goes for removing array members, but of course this time you test for the presence with equality:
db.collection.update(
{ "unique_array": 18 }, <-- existing element
{
"$pull": { "unique_array": 18 },
"$inc": { "size_of_array": -1 }
}
)
由于查询条件需要匹配,因此添加时如果数组元素已经存在,则不存在匹配,因此 $pull
的情况也是如此不在数组中.
Since the query condition needs to match, if the array element was already present when adding then there is no match and netiher the $push
or $inc
operations are run. And the same is true for the $pull
case where the element is not present in the array.
这篇关于仅向数组添加唯一性,并在更新时保持字段计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!