mongodbHow to convert MongoDB ObjectId to string?
MongoDB ObjectId is a 12-byte BSON type used as a unique identifier for documents within a collection. It can be converted to a string using the toString()
method.
Example code
const ObjectId = require('mongodb').ObjectId;
const id = new ObjectId();
const stringId = id.toString();
console.log(stringId);
Output example
5f3f9f9f9f9f9f9f9f9f9f9
Code explanation
const ObjectId = require('mongodb').ObjectId;
: This line imports the ObjectId class from the mongodb package.const id = new ObjectId();
: This line creates a new ObjectId instance.const stringId = id.toString();
: This line converts the ObjectId instance to a string.console.log(stringId);
: This line prints the string to the console.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to check the version of MongoDB?
- How to use triggers in MongoDB?
- How to work with time series data in MongoDB?
- How to use unwind in MongoDB?
- How to list MongoDB users?
- How to update many documents in MongoDB?
- How to create a many to many relation in MongoDB?
- How to perform a health check for MongoDB?
- How to query with "not in" condition in MongoDB?
See more codes...