如何将$ project ObjectId转换为mongodb中的字符串值?
问题描述:
在 aggregate 函数中是否可以使用运算符来获取字符串而不是ObjectId?
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"
}
}
}
])
反之亦然,使用 $toObjectId
聚合
db.collection.aggregate([
{
$project: {
_id: {
$toObjectId: "$_id"
}
}
}
])