Search code examples
javamongodbmorphia

Does MongoDB provide a way to generate sequential values?


I'm developing a web application in Java and storing some data on a MongoDB using Morphia.
Besides the ObjectId, I need to persist a sequential value for each document of a collection. This sequential value must be unique in the collection.

My first approach would be create a collection to store only the sequential value and synchronize the method which gets and increments the value.

Are there any better ways to do it?


Solution

  • Generally in MongoDB, you would not use an auto-increment pattern as it does not scale for databases with large numbers of documents. It is, however, possible to do this by using a separate counters collection to track the last number sequence used:

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

    You can then create a function that will return you the next number in the sequence:

    function getNextSequence(name) {
      var ret = db.counters.findAndModify(
             {
               query: { _id: name },
               update: { $inc: { seq: 1 } },
               new: true
             }
      );