Does MongoDB provide a way to generate sequential values?

回眸只為那壹抹淺笑 提交于 2019-12-13 07:44:31

问题


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?


回答1:


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
         }
  );


来源:https://stackoverflow.com/questions/29523127/does-mongodb-provide-a-way-to-generate-sequential-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!