I have an aggregation query whose MongoDB repsonse is :
_id: ObjectId('5e822d6c87502b3a9b751786')
I would like to get the string inside the ObjectId which is 5e822d6c87502b3a9b751786
.
[ Problem ]
I have searched this question but so far there are only three operators that are capable to do this, namely $toString
, $toObjectId
, and $convert
:
$project: {
_id: {
$toString: "$_id"
}
}
$project: {
_id: {
$toObjectId: "$_id"
}
}
$project: {
_id: {
$convert: {
input: "$_id"
to: "string"
}
}
}
MongoDB v3.6 does not support them if I am not mistaken.
Is there any workaround in MongoDB v3.6 to get a string inside an ObjectId?
Any help is much appreciated 🙂
2
Answers
Just want to add ray's answer after some findings.
Having defined a model in the app, here are some workaround that worked for me:
Same goes to aggregation :
Either
JSON.stringify()
ortoString()
can be used to convert it to string. Feel free to correct variable names.For MongoDB v3.6, as
$toString
and$convert
is not available until v4.0, you may need to resort to JS/application-level access to the_id
.output: