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.
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.
You should try $toString aggregation to convert ObjectId to string
db.strcoll.aggregate([
{ "$addFields": {
"collegeID": { "$toString": "$collegeDetail._id" }
}}
])
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;
The Link below will provide you javascript way to convert objectId to string: Convert ObjectID (Mongodb) to String in JavaScript