MongoDb:如果不存在,则将元素添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38970835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:48:36  来源:igfitidea点击:

MongoDb: add element to array if not exists

mongodb

提问by albert

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

我正在使用 node.js 和 Mongo.db(我刚开始使用 Mongo)。我有一个这样的文件:

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.

使用这个 JSON,它必须找到具有相同名称的标签并检查它是否在数组中videoId,如果没有,则将其插入到数组中。

How can I check the array and append data?

如何检查数组并附加数据?

回答by yellowB

You can use $addToSetoperator to check exist before append element into array.

您可以$addToSet在将元素追加到数组之前使用运算符检查是否存在。

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 videoIDsarray contains 34f54e34c. If not, append it to the array.

在这个更新语句示例中,mongoDB 会找到匹配的 TAG 文档name == sport,然后检查videoIDs数组中是否包含34f54e34c. 如果没有,请将其附加到数组中。

Detail usage of $addToSetplease read here.

详细用法$addToSet请阅读这里

回答by Maria Maldini

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:

如果你需要如何:在 nodeJs 实现中的 MongoDb,你可以从:

http://jsfiddle.net/1ku0z1a1/

http://jsfiddle.net/1ku0z1a1/

回答by Vora Ankit

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

$addToSet 运算符检查文档中的空数组或现有数组。

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