Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upserts in mongodb when using custom _id values

Tags:

mongodb

I need to insert a document if it doesn't exist. I know that the "upsert" option can do that, but I have some particular needs.

First I need to create the document with its _id field only, but only if it doesn't exist already. My _id field is a number generated by me (not an ObjectId). If I use the "upsert" option then I get "Mod on _id not allowed"

db.mycollection.update({ _id: id }, { _id: id }, { upsert: true });

I know that we can't use the _id in a $set.

So, my question is: If there any way to a "create if doesn't exists" atomically in mongodb?

EDIT: As proposed by @Barrie this works (using nodejs and mongoose):

var newUser = new User({ _id: id });
newUser.save(function (err) {               
    if (err && err.code === 11000) {            
            console.log('If duplicate key the user already exists', newTwitterUser);
        return;
    }
    console.log('New user or err', newTwitterUser);
});

But I still wonder if it is the best way to do it.

like image 773
aartiles Avatar asked Jan 13 '12 00:01

aartiles


People also ask

Can _ID be changed in MongoDB?

You cannot update it but you can save a new id and remove the old id. Follow some steps in order to update the _id of a MongoDB.

Why does MongoDB use _ID?

In MongoDB, _id field as the primary key for the collection so that each document can be uniquely identified in the collection. The _id field contains a unique ObjectID value. When you query the documents in a collection, you can see the ObjectId for each document in the collection.

What is Upserted in MongoDB?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.

Which of these defines a _id in MongoDB?

The _id Field In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.


1 Answers

I had the same problem, but found a better solution for my needs. You can use that same query style if you simply remove the _id attribute from the update object. So if at first you get an error with this:

db.mycollection.update({ _id: id }, {$set: { _id: id, name: 'name' }}, { upsert: true });

instead use this:

db.mycollection.update({ _id: id }, {$set: { name: 'name' }}, { upsert: true });

This is better because it works for both insert and update.

like image 103
Nate Barr Avatar answered Oct 13 '22 15:10

Nate Barr