3.45. Automatic growth of MongoDB

发布时间 : 2025-10-25 13:34:25 UTC      

Page Views: 10 views

MongoDB does not have the same automatic growth function as SQL, and MongoDB’s_ id is the 12-byte unique ID automatically generated by the system.

But in some cases, we may need to implement the ObjectId auto-growth feature.

Since MongoDB does not implement this function, we can do it programmatically. Now we will automatically grow the_ id field in the counters collection.

3.45.1. Use counters collections

Consider the following products documents. We want the_ id field to grow automatically from 1, 2, 3, 4 to n.

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

To do this, create a counters collection, and the sequence field values can be automatically long:

>db.createCollection("counters") 

Now let’s insert the following documents into the counters collection, using productid as the key:

{ "_id":"productid", "sequence_value": 0 } 

sequence_value A field is a value after the sequence is automatically incremented.

Use the following command to insert counters In the sequence document of the collection:

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

3.45.2. Create a Javascript function

Now, we create the function getNextSequenceValue as the input to the sequence name, and the specified sequence automatically grows by 1 and returns the latest sequence value. In the example in this article, the sequence is named productid.

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

3.45.3. Use the Javascript function

Next we will use the getNextSequenceValue Function to create a new document and set the document_ id automatically to the returned sequence value:

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

As you can see, we use getNextSequenceValue Function to set the_ id field.

To verify that the function is valid, we can read the document using the following command:

>db.products.find() 

The above command returns the following result, and we find that the_ id field is self-growing:

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"} { "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" } 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。