MongoDB

Create an Auto-Incrementing Sequence Field

Example:-
Use a dotnetfundacounter collection to track the last number sequence used. The _id field contains the sequence name and the seq field contains the last value of the sequence.

Insert into the dotnetfundacounter collection, the initial value for the userid:

 db.dotnetfundacounter.insert(  
{
_id: "userid",
seq: 0
}
)


Create a getNextSequenceBydoc function that accepts a docname of the sequence. The function uses the findAndModify() method to atomically increment the seq value and return this new value

 function getNextSequenceBydoc(docname) {   
var ret = db.dotnetfundacounter.findAndModify(
{
query: { _id: docname },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}

Use this getNextSequenceBydoc() function during insert()

 db.users.insert(  
{
_id: getNextSequenceBydoc("userid"),
Name: "Himen Patel"
}
)

Leave a comment