Mongodb 简明教程

MongoDB - Auto-Increment Sequence

MongoDB 没有像 SQL 数据库那样的开箱即用的自增功能。默认情况下,它使用 12 字节的 ObjectId 作为 _id 字段以唯一标识文档。但是,在某些情况下,我们可能希望 _id 字段具有 ObjectId 之外的某个自增值。

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId.

由于这不是 MongoDB 中的默认功能,我们将按照 MongoDB 文档中的建议使用 counters 集合编程来实现此功能。

Since this is not a default feature in MongoDB, we will programmatically achieve this functionality by using a counters collection as suggested by the MongoDB documentation.

Using Counter Collection

考虑一下以下 products 文档。我们希望 _id 字段从 1、2、3、4 到 n 都自增。

Consider the following products document. We want the _id field to be an auto-incremented integer sequence starting from 1,2,3,4 upto n.

{
  "_id":1,
  "product_name": "Apple iPhone",
  "category": "mobiles"
}

为此,创建一个 counters 集合,它将跟踪所有序列字段的最后一个序列值。

For this, create a counters collection, which will keep track of the last sequence value for all the sequence fields.

>db.createCollection("counters")

现在,我们将使用 productid 作为其键将以下文档插入到计数器集合中 −

Now, we will insert the following document in the counters collection with productid as its key −

> db.counters.insert({
	"_id":"productid",
	"sequence_value": 0
})
WriteResult({ "nInserted" : 1 })
>

字段 sequence_value 跟踪序列的最后一个值。

The field sequence_value keeps track of the last value of the sequence.

使用以下代码将此序列文档插入计数器集合中 −

Use the following code to insert this sequence document in the counters collection −

>db.counters.insert({_id:"productid",sequence_value:0})

Creating Javascript Function

现在,我们将创建一个函数 getNextSequenceValue ,它将以序列名称作为输入,将序列号增加 1,然后返回更新后的序列号。在我们的示例中,序列名称是 productid

Now, we will create a function getNextSequenceValue which will take the sequence name as its input, increment the sequence number by 1 and return the updated sequence number. In our case, the sequence name is productid.

>function getNextSequenceValue(sequenceName){
   var sequenceDocument = db.counters.findAndModify({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   });
   return sequenceDocument.sequence_value;
}

Using the Javascript Function

我们将在创建新文档并将其返回的序列值设为文档的 _id 字段时使用函数 getNextSequenceValue。

We will now use the function getNextSequenceValue while creating a new document and assigning the returned sequence value as document’s _id field.

使用以下代码插入两个示例文档 −

Insert two sample documents using the following code −

>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Apple iPhone",
   "category":"mobiles"
})
>db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Samsung S3",
   "category":"mobiles"
})

正如您所看到的,我们使用 getNextSequenceValue 函数为 _id 字段设置值。

As you can see, we have used the getNextSequenceValue function to set value for the _id field.

为了验证此功能,让我们使用 find 命令获取文档 −

To verify the functionality, let us fetch the documents using find command −

>db.products.find()

上述查询返回了以下具有自增 _id 字段的文档 −

The above query returned the following documents having the auto-incremented _id field −

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}
{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }