Adding an element to an array in MongoDb only if it doesn’t already exist [similar question]

I possess a document structured in a way that the server gets a JSON format containing a specific tag name. The server’s task is to examine the array and determine if the tag name exists within it. If not, it must add the tag name to the array. My concern is how to efficiently scan the array and append the missing data.

Question:

I am currently utilizing both node.js and Mongo.db, with my recent adoption of Mongo. Specifically, I am working with a document structured in the following way:

Tag : {
   name: string,
   videoIDs: array
}

The concept is that a JSON is sent to the server.

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

Using the provided JSON, the program must locate the tag with a matching name and verify whether the

videoId

is present in the array. If it is not, it should be added to the array.

What is the process to inspect the array and add information to it?


Solution 1:

Utilize the

$addToSet

operator to incorporate
check exist
prior to inserting
append element
into an array.

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

This example of an update statement entails mongoDB’s process of searching for a TAG document that corresponds with

name == sport

. After that, it examines whether the

videoIDs

array encompasses

34f54e34c

. If not, it will add

34f54e34c

to the array.

For further information on how to use

$addToSet

, please refer to this document.


Solution 2:


Although I haven’t tested it, you could attempt something along the lines of:

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

To begin implementing MongoDb in nodeJs, you can initiate with the following steps.

http://jsfiddle.net/1ku0z1a1/


Solution 3:


The

$addToSet

checks whether the document’s array is empty or exists.

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

Frequently Asked Questions