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.
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.
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.
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"}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With