Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

People also ask

How do I add an element to an array of objects in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

How do you update an array element in MongoDB?

Learn how to update array fields in documents in MongoDB collections. You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I use $addToSet in MongoDB?

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. The $addToSet operator has the form: { $addToSet: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

How do I change the nested array element in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


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"}})