Syntax error Auto increment in MongoDB to store sequence of Unique User ID?

Auto increment in MongoDB to store sequence of Unique User ID?



To auto increment in MongoDB to store a sequence of unique user id, let us create a collection which contains information about last sequence values of all documents.

Let us first create a collection. The query to create a collection which is as follows −

> db.createSequenceDemo.insertOne({_id:"SID",S_Value:0});
{ "acknowledged" : true, "insertedId" : "SID" }

Now, we will create a function that will generate an auto increment in MongoDB to store sequence. The query is as follows −

> function nextSequence(s) {
   ... var sd = db.createSequenceDemo.findAndModify({
      ... query:{_id: s },
      ... update: {$inc:{S_Value:1}},
      ... new:true
   ... });
   ... return sd.S_Value;
... }

Let us create a collection with some documents and call the above function in order to generate a sequence of unique user id.

The query to create a collection with a document is as follows −

> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Larry","StudentMathMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f61008d10a061296a3c40")
}
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Mike","StudentMathMarks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f61118d10a061296a3c41")
}
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Sam","StudentMathMarks":67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f611d8d10a061296a3c42")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.checkSequenceDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7f61008d10a061296a3c40"),
   "StudentId" : 1,
   "StudentName" : "Larry",
   "StudentMathMarks" : 78
}
{
   "_id" : ObjectId("5c7f61118d10a061296a3c41"),
   "StudentId" : 2,
   "StudentName" : "Mike",
   "StudentMathMarks" : 89
}
{
   "_id" : ObjectId("5c7f611d8d10a061296a3c42"),
   "StudentId" : 3,
   "StudentName" : "Sam",
   "StudentMathMarks" : 67
}

Look at the field “StudentId” which is auto incremented by 1

Updated on: 2019-07-30T22:30:25+05:30

950 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements