MongoDb: add element to array if not exists [duplicate] MongoDb: add element to array if not exists [duplicate] mongodb mongodb

MongoDb: add element to array if not exists [duplicate]


You can use $addToSet operator to check exist before append element into array.

db.tags.update(    {name: 'sport'},    {$addToSet: { videoIDs: "34f54e34c" } });

In this update statement example, mongoDB will find the TAG document which matches name == sport, and then check whether the videoIDs array contains 34f54e34c. If not, append it to the array.

Detail usage of $addToSet please read here.


I didn't test it, but you can try something like:

yourDb.find({ name: "sport",               videoIDs: { $in: ["34f54e34c"] } })      .update({$addToSet: { videoIDs: "34f54e34c" }});

If you need how: MongoDb in nodeJs implementation, you can start with:

http://jsfiddle.net/1ku0z1a1/


$addToSet operator check for the empty or existing array in document.

 db.col_name.update({name :"name_for_match"},{$addToSet :  { videoId : "video_id_value"}})