Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB insert without duplicates

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.

like image 904
Austin Avatar asked Oct 26 '25 04:10

Austin


1 Answers

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

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

like image 59
cjungel Avatar answered Oct 28 '25 17:10

cjungel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!