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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)