MongoDB自动增长的实现
因为 MongoDB 中没有实现这个功能,所以我们需要通过编程的方式来实现。本节中我们将通过两个(counters 和 tutorials)来实现自动递增功能,其中 counters 用来记录自动递增的数值,tutorials 用来存储具体的数据。
使用 counters
假如有以下文档,我们希望 _id 字段以 1、2、3、...、n 的自动递增整数顺序排列。我们将在 counters 中插入以下文档:{
"_id":1,
"tutorials_name": "MongoDB 教程",
"url": "http://www.biancheng网站站点" rel="nofollow" />
> db.createCollection("counters")
{ "ok" : 1 }
其中 _id 字段的值为 productid,sequence_value 字段的值默认为零,用来保存自动增长后的一个值。> db.counters.insert({_id:"productid",sequence_value:0})
WriteResult({ "nInserted" : 1 })
创建 Javascript 函数
下面我们创建一个名为 getNextSequenceValue 的函数,它能够以序列名作为参数,并将序列号递增 1,然后返回更新后的序列号。> function getNextSequenceValue(sequenceName){
... var sequenceDocument = db.counters.findAndModify(
... {
... query:{_id: sequenceName },
... update: {$inc:{sequence_value:1}},
... "new":true
... });
... return sequenceDocument.sequence_value;
... }
使用 Javascript 函数
下面我们创建一个新的,在向中插入数据时使用 getNextSequenceValue() 函数来定义 _id 字段的值,示例代码如下:> db.tutorials.insert({
... "_id":getNextSequenceValue("productid"),
... "tutorials_name": "MongoDB 教程",
... "url": "http://www.biancheng网站站点" rel="nofollow" />
> db.tutorials.find().pretty()
{
"_id" : 1,
"tutorials_name" : "MongoDB 教程",
"url" : "http://www.biancheng网站站点" rel="nofollow" />