Add Unique only to array and keep field count on update

♀尐吖头ヾ 提交于 2019-12-13 02:05:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!