3

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.

4
  • This is not currently supported, but will be available in an upcoming release. See here. Commented May 30, 2018 at 17:03
  • Isn't there any workaround possible? Commented May 30, 2018 at 17:05
  • I can't see anything out there - all solutions talk of doing it in the JavaScript context, outside of an aggregation pipeline, which I guess is not what you are looking for. Commented May 30, 2018 at 17:07
  • Exactly. Will scavenge more about it. Thanks. Commented May 30, 2018 at 17:09

3 Answers 3

4

You should try $toString aggregation to convert ObjectId to string

db.strcoll.aggregate([ { "$addFields": { "collegeID": { "$toString": "$collegeDetail._id" } }} ]) 
Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

1

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

1 Comment

Thanks for the help, but as you see in the question I wanted to do it in the query itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.