0

I want to generate a User Record Number automatically. When a new user is added, they get assigned a User Record Number. The User Record Number follows this format: “US-000000”. The first user added to a account will be User Record Number US-000001.

How to do this? Is there any way in mongodb to autoincrement on based on a format as in SQL Server?

Anup
  • 9,396
  • 16
  • 74
  • 138
  • check these links : http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ http://stackoverflow.com/questions/14454271/auto-increment-document-number-in-mongo-mongoose – Saheed Hussain Jun 02 '14 at 13:25

1 Answers1

2

As far as I know, MongoDB does not feature any form of automatic incrementation, not even for the automatically generated _id fields, as this does not work well wit hthe clustered, non-centralised nature of the system.

The only way to achieve this is trying to work it out with atomar operations like findAndModify or similar, and create the incremented ID in your application.

As a suggestion, Keep a field like this in the collection:

{
    "_id": "incr",
    "n": 42
}

Whenever you add a new document, read the value via findAndModify and $inc it right away - that way your counter is always correctly incremented and you get the correct number to add.

Lanbo
  • 15,118
  • 16
  • 70
  • 147
  • Would be nice if you changed the operator mentioned to [**`$inc`**](http://docs.mongodb.org/manual/reference/operator/update/inc/) which is the actual operator. For the record there is a documented tutorial on handling [auto-incremented fields](http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/) in the official manual. – Neil Lunn May 31 '14 at 10:23
  • Do will i need to create a new collection for this? – Anup May 31 '14 at 10:30
  • @Anup no you just put the document above in the same collection. As long as the `_id` won't overlap, there's no problem. – Lanbo May 31 '14 at 10:32
  • When i put the document above in the same collection..When i retrieve list of all users...this record also comes with everything null..! – Anup Jun 02 '14 at 07:04
  • @Anup Then add `_id : { $ne : 'incr' }` to your `findAll` query. – Lanbo Jun 02 '14 at 07:14
  • Thats exactly what i did... :) – Anup Jun 02 '14 at 07:17
  • This thing works in RoboMongo....but same query gives no results in my code...! `User.find({ '_id': { $ne: 'incr' } }, ....` – Anup Jun 02 '14 at 07:22
  • @Anup can't help your there, make a new question for that or search older ones. – Lanbo Jun 02 '14 at 07:25
  • As i solved this issue....further i found that my search query also brings a null record.....I think i should make a new collection specially for Auto Increment...!! – Anup Jun 02 '14 at 08:42