Represents an ObjectId that can be used as an _id in the DataAPI.

Provides methods for generating ObjectIds and getting the timestamp of an ObjectId.

Example

const collection = await db.createCollection('myCollection'. {
  defaultId: {
  type: 'objectId',
  },
});

await collection.insertOne({ album: 'Inhuman Rampage' });

const doc = await collection.findOne({ album: 'Inhuman Rampage' });

// Prints the ObjectId of the document
console.log(doc._id.toString());

// Prints the timestamp when the document was created (server time)
console.log(doc._id.getTimestamp());

Example

await collection.insertOne({ _id: new ObjectId(), album: 'Sacrificium' });

const doc = await collection.findOne({ album: 'Sacrificium' });

// Prints the ObjectId of the document
console.log(doc._id.toString());

// Prints the timestamp when the document was created (server time)
console.log(doc._id.getTimestamp());

Constructors

Properties

Methods

Constructors

  • Creates a new ObjectId instance.

    If id is provided, it must be a 24-character hex string. Otherwise, a new ObjectId is generated.

    Parameters

    • Optional id: null | string | number

      The ObjectId string.

    • validate: boolean = true

      Whether to validate the ObjectId string. Defaults to true.

    Returns ObjectId

Properties

_raw: string

Methods

  • Compares this ObjectId to another ObjectId.

    The other ObjectId can be an ObjectId instance or a string.

    An ObjectId is considered equal to another ObjectId if their string representations are equal.

    Parameters

    • other: unknown

      The ObjectId to compare to.

    Returns boolean

    true if the ObjectIds are equal, false otherwise.

  • Returns the timestamp of the ObjectId.

    Returns Date

    The timestamp of the ObjectId.

  • Converts the ObjectId to a JSON representation.

    Serializes to { $objectId: 'objectId' }.

    Returns {
        $objectId: string;
    }

    • $objectId: string
  • Returns the string representation of the ObjectId.

    Returns string