Skip to content

MongoDB convert ObjectId to string in query

  • by
MongoDB convert ObjectId to string in query

1. Overview

In this article, we will learn to convert ObjectId to string in MongoDB query. You can learn more about MongoDB by using these articles.

2. MongoDB ObjectId

MongoDB is a 12-byte BSON field that is automatically generated by MongoDB and assigned to the _id field of each document. ObjectID can be considered globally unique across all documents. 

You can also specify a 24-character hexadecimal string value for the new ObjectId.

y = ObjectId("507f191e810c19729de860ea")

It comprises

  • A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.
  • A 5-byte random value generated once per process. This random value is unique to the machine and process.
  • A 3-byte incrementing counter, initialized to a random value.

3. Convert ObjectId to string in MongoDB query

Often you could have written MongoDB queries to return _id along with other fields of a document.

Usually, it would return _id of type ObjectId.

For example, the following MongoDB query uses the aggregate function to project _id field.

Atlas atlas-kd7riz-shard-0 [primary] sample-supplies> db.sales.aggregate([{
...     $project: {
.....         _id: '$_id'
.....     }
... }])
[
  { _id: ObjectId("5bd761dcae323e45a93ccfea") },
  { _id: ObjectId("5bd761dcae323e45a93ccff4") },
  { _id: ObjectId("5bd761dcae323e45a93ccfed") }
]
Type "it" for more

Result contains the _id of type ObjectId.

3.1. ObjectId to string from v2.6

Previously, we have learned to create a new ObjectId by passing a hexadecimal string as an argument to the constructor.

You can use the str attribute of the ObjectId to get the _id as a hexadecimal String value. After you retrieve the results from the MongoDB query, you can call str attribute to get the String value.

ObjectId("507f191e810c19729de860ea").str
Returns value
507f191e810c19729de860ea

3.2. convert ObjectId to String from v4.0

MongoDB 4.0 introduces $toString (aggregation) operator to get certain fields such as ObjectId, Date, Boolean, Double, Decimal, and Long data types as a string.

If $toString cannot convert a value to a string, it throws an error. If the value is null or missing, $toString returns null.

$toString has the following syntax:

{   $toString: <expression>}

By using the above operator, you can get _id as an String object.

db.sales.aggregate([
{ $project: 
   { _id: { 
     '$toString': '$_id' 
}} 
}])

If you execute the above DB query, it produces the following result where the _id field is of type String instead of ObjectId.

Atlas atlas-kd7riz-shard-0 [primary] sample-supplies> db.sales.aggregate([{ $project: { _id: { '$toString': '$_id' }} }])
[
  { _id: '5bd761dcae323e45a93ccfea' },
  { _id: '5bd761dcae323e45a93ccff4' },
  { _id: '5bd761dcae323e45a93ccfed' }
]
Type "it" for more

4. Conclusion

To sum up, we have learned to retrieve ObjectId to string in MongoDB query.

Leave a Reply

Your email address will not be published. Required fields are marked *