ObjectId.toString()
Returns the string representation of the
ObjectId()
.
Compatibility
You can use ObjectId.toString()
for deployments hosted in the following environments:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
- MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
- MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Example
The following example:
- Generates a new
ObjectId()
and stores it in the variablemyObjectId
. - Creates a string representation of
myObjectId
using thetoString()
method. - Stores the string representation in the variable
myObjectIdString
.
Run the following commands in mongosh
:
myObjectId = ObjectId("507c7f79bcf86cd7994f6c0e")
myObjectIdString = myObjectId.toString()
The operation returns the following string:
507c7f79bcf86cd7994f6c0e
To confirm the type of myObjectIdString
, use the typeof
JavaScript operator:
typeof myObjectIdString
The operation returns the following: