MongoDb: Difference between $push/$addtoset

后端 未结 6 689
迷失自我
迷失自我 2020-12-08 09:06

I read the documentation in the MongoDb and I used a simple proves and I only look that: Push is sorting the array but addtoSet isn\'t it.

For me visual

6条回答
  •  猫巷女王i
    2020-12-08 09:27

    $push - adds items in the order in which they were received. Also you can add same items several times.

    $addToSet - adds just unique items, but order of items is not guaranteed.

    If you need to add unique items in order, you can group and add elements via $addToSet, then $unwind the array with elements, $sort by items, and then do $group again with $push items.

提交回复
热议问题