Brigitmerito Brigit
Brigitmerito Brigit

Reputation: 3

mongodb second userid field with auto increment

I want to have an additional ID field in my mongodb collection. The objectId is perfect for get unique IDs, but I need shorter IDs for my user management. These IDs should look like 10001, 10002 and so on. Is it possible to get these by auto increment?

Upvotes: 0

Views: 202

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

You can do by creating your own javascript function and creating a new collection which can keep the track of the next sequence number. There are different tutorials available for this to implement. A function that can help you to fetch last sequence and increment it:

//create a new collection in Mongo Shell
db.createCollection("collectionName");
db.collectionName.insert({_id:"productid",sequence_value:0})
function geSequenceValue(sequenceName){
   var sequenceDocument = db.CollectionName.findAndModify({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   });
   return sequenceDocument.sequence_value;
}

//MongodB shell command
>db.collectionName.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"IPhone",
   "category":"Mobile"
})

For reference you can follow check this.

Upvotes: 1

Related Questions