How to create an Auto-Incrementing field in MongoDB?


Create an Auto-Incrementing
 I checked so many article related to this but all are confusing for me because i was new in MongoDB
and i want to create a field which should be auto increment like MySql.
So i got an article on docs.mongodb.org and find that this article is great
Here are some steps that how you can create an auto-increament id in your MongoDB
Open your MongoDB screen where you write command line query
Run this command and check database
Step 1. show dbs - This command will show all database from your MongoDB
Step 2. use databasename -  choose your database where you want to
create a collection and auto increment field
Now create new collection
Step 3. db.createCollection("user");
Step 4. db.counters.insert(
   {
      _id: "userid",
      seq: 0
   }
)

Now you need to create a function for auto increment the _id in mongoDB
so create a function in your mongodb
You need to write this function on your mongoDB screen just after the above command
Step 5. function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );

   return ret.seq;
}

Step 6. db.user.insert(
   {
     _id: getNextSequence("userid"),
     name: "PHP developer"
   }
)

db.user.insert(
   {
     _id: getNextSequence("userid"),
     name: "Mongo Db developer"
   }

Now you can check your record in your mongoDB with this command
db.users.find()
I hope you understand now that how its works!

Comments