没有重复的MongoDB插入 [英] MongoDB insert without duplicates

查看:55
本文介绍了没有重复的MongoDB插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在运行mongodb,我刚刚意识到,我正在插入集合中,但不确定是否要防止重复.这是我的插入方式:

  function insertCompanies(companyID,companyURL,companyAppID){MongoClient.connect(URL,function(err,db){如果(错误){console.log(err);} 别的 {console.log(我们已连接");}var collection = db.collection('Companies');var company = {"companyProfileID":companyID,"URL":companyURL,"appID":companyAppID};collection.insert(company,function(err,result){如果(错误){console.log(err);} 别的 {console.log(result);}});db.close();});} 

我正在使用NodeJS.当用户调用 insertCompanies 方法时,如果公司已经存在(通过 companyID URL ),则该集合似乎允许重复./p>

是否有其他防止重复的插入功能?我环顾四周,找不到适合我的直接解决方案.

解决方案

而不是 db.insert(),您应该使用 db.update()并指定 $ upsert:是.

https://docs.mongodb.com/v3.2/reference/method/db.collection.update/

Right now I am running mongodb and I just realized, I am inserting into collections and I am not sure if I am preventing duplicates. Here is how I am inserting:

function insertCompanies(companyID, companyURL, companyAppID) {
    MongoClient.connect(url, function(err, db) {
        if (err) {
            console.log(err);
        } else {
            console.log("We are connected");
        }

        var collection = db.collection('Companies');
        var company = {
            "companyProfileID": companyID,
            "url": companyURL,
            "appID": companyAppID
        };
        collection.insert(company, function(err, result) {
            if (err) {
                console.log(err);
            } else {
                console.log(result);
            }
        });
        db.close();
    });
}

I am using NodeJS. When a user calls the insertCompanies method, if the company already exists (via companyID or URL), it seems like the collection allows duplicates.

Is there a different insert function that prevents duplicates? I looked around and could not find a straight forward solution tailored to me.

解决方案

Instead of db.insert() you should use db.update() and specify $upsert: true.

https://docs.mongodb.com/v3.2/reference/method/db.collection.update/

这篇关于没有重复的MongoDB插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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