English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
MongoDB does not have a built-in automatic increment feature like SQL databases. By default, it will_id
field12The byte ObjectId is used as the primary key to uniquely identify the document. However, in some cases, we may want the _id field to have some automatically incremented values in addition to ObjectId.
Since this is not a default feature in MongoDB, we will use}}counters
Programmatically implement this function as recommended by the MongoDB document collection.
See the followingproducts
document. We hope the _id field is an auto-incrementing integer starting from1,2,3,4to n auto-incrementing integer sequence.
{ "_id":1, "product_name": "Apple iPhone" "category": "mobiles" }
To do this, create acounters
collection, which will track the last sequence value of all sequence fields.
>db.createCollection("counters")
Now, we will create the following documentproductid
insert it as a key into the counters collection-
> db.counters.insert({ "_id":"productid", "sequence_value": 0 ) WriteResult({ "nInserted": 1 ) >
The sequence_value field tracks the last value of the sequence.
Use the following code to insert this sequence document into the counters collection-
>db.counters.insert({_id:"productid",sequence_value:0})
Now, we will create a functiongetNextSequenceValue
,the function takes the sequence name as input, and increments the sequence number by1and return the updated sequence number. In our example, the sequence name isproductid
。
>function getNextSequenceValue(sequenceName){ var sequenceDocument = db.counters.findAndModify({ query:{_id: sequenceName }, update: {$inc:{sequence_value:1}}, new: true }); return sequenceDocument.sequence_value; }
Now, we will use the getNextSequenceValue function when creating a new document and assigning the returned sequence value to the document's _id field.
Insert the following code to insert two sample documents-
>db.products.insert({ "_id": getNextSequenceValue("productid"), "product_name":"Apple iPhone", "category": "mobiles" ) >db.products.insert({ "_id": getNextSequenceValue("productid"), "product_name": "Samsung S"3, "category": "mobiles" )
As you can see, we used the getNextSequenceValue function to set the value of the _id field.
To verify the functionality, let's use the find command to retrieve the document-
>db.products.find()
The query above returned the following documents with an auto-incrementing _id field-
{ "_id": 1, "product_name": "Apple iPhone", "category": "mobiles" { "_id": 2, "product_name": "Samsung S"3"category": "mobiles"