如何在mongodb/node.js中向现有集合添加自动增量? [英] How to add auto increment to existing collection in mongodb/node.js?

查看:189
本文介绍了如何在mongodb/node.js中向现有集合添加自动增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法或软件包可以帮助我向现有集合中添加自动增量?互联网上充满了有关如何在创建馆藏之前添加AI的信息,但是我没有找到有关在馆藏已经存在时如何添加AI的信息...

Is there any methods or packages, that can help me add auto increments to existing collection? Internet full of information, about how to add AI before you create collection, but I did not find information on how to add AI when collection already exist...

推荐答案

MongoDB没有内置的自动增量功能.

MongoDB does not have an inbuilt auto-increment functionality.

创建一个新集合以跟踪用于插入的最后一个序列值:

Create a new collection to keep track of the last sequence value used for insertion:

db.createCollection("counter")

它将仅保留一个记录,如下:

It will hold only one record as:

db.counter.insert({_id:"mySequence",seq_val:0})

创建一个JavaScript函数为:

Create a JavaScript function as:

function getNextSequenceVal(seq_id){
   // find record with id seq_id and update the seq_val by +1
   var sequenceDoc = db.counter.findAndModify({
      query:{_id: seq_id},
      update: {$inc:{seq_val:1}},
      new:true
   });

   return sequenceDoc.seq_val;
}

要更新现有集合中所有已存在的值,这应该可以工作(对于空的{},如果您只想更新某些文档,则可以放置条件):

To update all the already existing values in your existing collection, this should work (For the empty {}, you can place your conditions if you want to update some documents only):

db.myCollection.update({},
   {$set:{'_id':getNextSequenceVal("mySequence")}},{multi:true})

现在,您可以通过以下方式将新记录插入到现有集合中:

Now you can insert new records into your existing collection as:

db.myCollection.insert({
   "_id":getNextSequenceVal("mySequence"),
   "name":"ABC"
})

这篇关于如何在mongodb/node.js中向现有集合添加自动增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆