MongoDb: add element to array if not exists

Mongodb

Mongodb Problem Overview


I'm using node.js and Mongo.db (I'm newly on Mongo). I have a document like this:

Tag : {
   name: string,
   videoIDs: array
}

The idea is, the server receives a JSON like

JSON: { 
    name: "sport",
    videoId: "34f54e34c"
}

with this JSON, it has to find the tag with the same name and check if in the array it has the videoId, if not, insert it to the array.

How can I check the array and append data?

Mongodb Solutions


Solution 1 - Mongodb

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.

Solution 2 - Mongodb

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/

Solution 3 - Mongodb

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlbert Lázaro de LaraView Question on Stackoverflow
Solution 1 - MongodbyellowBView Answer on Stackoverflow
Solution 2 - MongodbMaria MaldiniView Answer on Stackoverflow
Solution 3 - MongodbVora AnkitView Answer on Stackoverflow