MongoDb: add element to array if not exists [duplicate]
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?
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"}})