Just like in MYSQL, I want an incrementing ID.
MongoDB provides 2 way to auto increment _id (or custom key) .
Here we need to create collection which stores the maximum number of keys and increment by 1 every time when we call this function.
1. STORE FUNCTION
function getNextSequence(collectionName) {
var ret = db.counters.findAndModify({
query: { _id: collectionName },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
});
return ret.seq;
}
2. INSERT DOC
db.users.insert({
_id: getNextSequence("USER"),
name: "Nishchit."
})
In this pattern, an Optimistic Loop calculates the incremented _id value and attempts to insert a document with the calculated _id value. If the insert is successful, the loop ends. Otherwise, the loop will iterate through possible _id values until the insert is successful.
1. STORE FUNCTION
function insertDocument(doc, targetCollection) {
while (1) {
var cursor = targetCollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);
var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;
doc._id = seq;
var results = targetCollection.insert(doc);
if( results.hasWriteError() ) {
if( results.writeError.code == 11000 /* dup key */ )
continue;
else
print( "unexpected error inserting data: " + tojson( results ) );
}
break;
}
}
2. INSERT DOC
var myCollection = db.USERS;
insertDocument(
{
name: "Nishchit Dhanani"
},
myCollection
);
Official doc from MongoDB.