我在集合中存储了一个项目数组(stringId)。该数组中的所有元素都必须是唯一的。所以我使用 $addToSet 来推送我的项目。
但是,我还想在同一请求中设置字段中数组的大小:
{
unique_array: ['12', '20', '18'],
size_of_array: 3
}
=> 添加到集合 15
{
unique_array: ['12', '20', '18', '15'], => Add to set
size_of_array: 4 => Incremented
}
=> 添加到集合 18
{
unique_array: ['12', '20', '18', '15'], => Already in the set
size_of_array: 4 => Not incremented
}
谢谢!
最佳答案
对于此类操作,您不应使用 $addToSet
当然,因为 $inc
无论是否向数组添加任何内容(“set”),都会发生。
相反,使用 $ne
测试数组查询中的运算符:
db.collection.update(
{ "unique_array": { "$ne": 18 } }, <-- existing element
{
"$push": { "unique_array": 18 },
"$inc": { "size_of_array": 1 }
}
)
删除数组成员也是如此,但是这次当然要测试是否存在相等:
db.collection.update(
{ "unique_array": 18 }, <-- existing element
{
"$pull": { "unique_array": 18 },
"$inc": { "size_of_array": -1 }
}
)
由于查询条件需要匹配,如果添加时数组元素已经存在则不匹配,$push
或 $inc
操作运行。 $pull
也是如此。数组中不存在该元素的情况。
关于mongodb - 仅将唯一添加到数组并在更新时保留字段计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119850/