问题
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
}
=> Add to set 15
{
unique_array: ['12', '20', '18', '15'], => Add to set
size_of_array: 4 => Incremented
}
=> Add to set 18
{
unique_array: ['12', '20', '18', '15'], => Already in the set
size_of_array: 4 => Not incremented
}
Thanks !
回答1:
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.
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 }
}
)
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.
来源:https://stackoverflow.com/questions/36119850/add-unique-only-to-array-and-keep-field-count-on-update