MongoDB - Prevent duplication in your arrays
$push vs $addToSet
Search for a command to run...
$push vs $addToSet
No comments yet. Be the first to comment.
This serie gather all the new things I learn on a day to day basis that can be usefull for everyone. It can be about anything, tech, books, people, hack, etc.
Angular concept AKA ngIf
Aggregation pipeline
Angular concept AKA ngIf
What's the difference between them?
The "sparse" option
When we want to insert data in an array in Mongo we use $push . But it won't prevent you from inserting multiple times the same value in your array.
If you want to ensure that there's no duplication.
You can use : $addToSet
When you want to insert an element inside an array, $addToSet will check if this element already exists and if that's the case, will keep the existing one without pushing the element (but it will update your updatedAt field).
If your array doesn't exist yet, it will create and push the element inside it.
$addToSet work only on array field