3.38. MongoDB ObjectId

发布时间 :2025-10-25 12:32:57 UTC      

We have used MongoDB’s object Id (ObjectId) in the previous chapters.

In this chapter, we will learn about the structure of ObjectId.

ObjectId is a 12-byte BSON type data in the following format:

  • The first four bytes represent a timestamp

  • The next three bytes are machine identification codes.

  • The next two bytes are made up of process id (PID)

  • The last three bytes are random numbers.

Documents stored in MongoDB must have a “_ id” key. The value of this key can be of any type, and the default is an ObjectId object.

在一个集合里面,每个文档都有唯一的”_id”值,来确保集合里面每个文档都能被唯一标识。

MongoDB uses ObjectId rather than the main reason for other more conventional practices, such as auto-incrementing primary keys, because it is laborious and time-consuming to increase primary key values synchronously on multiple servers.

3.38.1. Create a new ObjectId

Generate a new ObjectId using the following code:

>newObjectId = ObjectId()

The above statement returns the following unique generated id:

ObjectId("5349b4ddd2781d08c09890f3")

You can also use the generated id instead of the ObjectId automatically generated by MongoDB:

>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")

3.38.2. Timestamp when the document was created

Because the 4-byte timestamp is stored in ObjectId, you don’t need to save the timestamp field for your document, you can use the getTimestamp function to get the creation time of the document:

>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()

The above code returns the creation time of the document in ISO format:

ISODate("2014-04-12T21:49:17Z")

3.38.3. Convert ObjectId to string

In some cases, you may need to convert ObjectId to string format. You can use the following code:

>new ObjectId().str

The above code returns a string in Guid format:

5349b4ddd2781d08c09890f3

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.