iatsi
iatsi

Reputation: 151

Convert ObjectId to String in the MongoDB

I have an aggregate query.

{ "$addFields": {
  "collegeID": (('$collegeDetail._id')),
}}

where, I want to add a new field 'CollegeID' as a string version of the ObjectId stored in collegeDetail._id.

Any help will be appreciated. Thanks.

Upvotes: 3

Views: 5302

Answers (3)

Ashh
Ashh

Reputation: 46451

You should try $toString aggregation to convert ObjectId to string

db.strcoll.aggregate([
  { "$addFields": {
    "collegeID": { "$toString": "$collegeDetail._id" }
  }}
])

Upvotes: 3

Syed Ahsan Ali
Syed Ahsan Ali

Reputation: 23

The Link below will provide you javascript way to convert objectId to string: Convert ObjectID (Mongodb) to String in JavaScript

Upvotes: 1

iatsi
iatsi

Reputation: 151

Edit: Starting from (Version 4.0 of MongoDB) Gladly MongoDB has made and update and got us a new operator that does this job.

$convert

This can be used to change the data type of value from almost each type to each type

For more information check it up here: https://docs.mongodb.com/manual/reference/operator/aggregation/convert/

Hope this helps;

Upvotes: 1

Related Questions