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 two operators which are $toString
and $toObjectId
:
$project: {
_id: {
$toString: "$_id"
}
}
$project: {
_id: {
$toObjectId: "$_id"
}
}
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 :)
CodePudding user response:
Use $convert
{
$project: {
_id: {
$convert: {
input: "$_id",
to: "string"
}
}
}
CodePudding user response:
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
.
db.testCollection.insertMany([
{
"_id": ObjectId("5e822d6c87502b3a9b751786")
}]);
db.testCollection.find().forEach( doc => {
// put your logic for process here
console.log(JSON.stringify(doc._id))
});
output:
"5e822d6c87502b3a9b751786"