📌  相关文章
📜  MongoDB-ObjectId(1)

📅  最后修改于: 2023-12-03 15:03:02.039000             🧑  作者: Mango

MongoDB ObjectId

MongoDB ObjectId is a 12-byte unique identifier for documents in a MongoDB collection. It consists of:

  • A 4-byte timestamp value, representing the ObjectId's creation time
  • A 5-byte random value
  • A 3-byte incrementing counter, initialized to a random value

The unique combination of these three values ensures that each ObjectId is almost certainly unique.

Usage

In MongoDB, ObjectId is commonly used as the _id field for documents. When creating a new document without specifying an _id value, MongoDB automatically generates a new ObjectId.

db.mycollection.insertOne({"name": "John", "age": 30});

This will generate a new document with an ObjectId as its _id field:

{
    "_id" : ObjectId("5fa9b90516ebd13a1460b3c7"),
    "name" : "John",
    "age" : 30
}

We can also create a new ObjectId manually:

var objectId = new ObjectId();
Retrieving Timestamp

We can retrieve the timestamp from an ObjectId by calling its getTimestamp() method:

var objectId = ObjectId("5fa9b90516ebd13a1460b3c7");
var timestamp = objectId.getTimestamp();

This will return a Date object representing the ObjectId's creation time.

Conclusion

MongoDB ObjectId is a unique identifier for documents in a MongoDB collection. It consists of a timestamp, random value, and incrementing counter. It is commonly used as the _id field for documents and can be generated automatically by MongoDB or manually using the ObjectId() constructor. Retrieving the timestamp from an ObjectId is also possible using the getTimestamp() method.