MongoDb:将元素添加到数组(如果不存在) [英] MongoDb: add element to array if not exists

查看:400
本文介绍了MongoDb:将元素添加到数组(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Tag : {
   name: string,
   videoIDs: array
}

想法是,服务器会收到

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

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

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?

推荐答案

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

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

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

在此更新语句示例中,mongoDB将找到与name == sport匹配的TAG文档,然后检查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.

$addToSet的详细用法,请在此处中阅读.

Detail usage of $addToSet please read here.

这篇关于MongoDb:将元素添加到数组(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆