Is there an operator I could use in aggregate function to get a string instead of ObjectId in response?
db.something.aggregate([
{ "$match": { "property": { "$exists": true } } },
{ "$project": { "stringId": "$_id.???" } }
])
Mongodb 4.0 has introduced $toString aggregation operator. So, Now you can easily convert ObjectId to string
db.collection.aggregate([
{
$project: {
_id: {
$toString: "$_id"
}
}
}
])
OR vice versa using $toObjectId aggregation
db.collection.aggregate([
{
$project: {
_id: {
$toObjectId: "$_id"
}
}
}
])
There is no Direct Operator in aggregate function to get String from ObjectId.
After version 2.6 You can use ObjectId.toString() method to convert your ObjectId to string. First you match and project your ObjectID. Then you can convert this object ID to string by using ObjectID.toString().
db.something.aggregate([{"$match":{'property': {$exists:true}}},{"$project":{"_id":1}}])
And then use resulting Object and get the string as response using ObjectID.tostring()
Edit: You can access the str attribute of the object id using
ObjectId("507f191e810c19729de860ea").str
source: mongodb docs
You can do it inline using the $concat operator:
db.something.aggregate(
[
{ $match :
{ 'property' :
{ $exists:true }
}
},
{ $project:
{ stringId:
{ $concat: [ ObjectId().str ] }
}
}
]
)
$substrand numeric to Date or Date to numeric is basically possible with trickery ). Why would you think this is needed anyway? It's fairly simple in most languages to write theObjectIdvalue as a string anyway.{ "$oid": "56ea9e8bb1e015d13b376db5" }since at least that lets a remote client know that the data is indeed anObjectIdso it can parse and cast correctly itself. That's a good thing, especially considering that storage is half the bytes of the string length.