如何将$ project ObjectId转换为mongodb中的字符串值? [英] how to $project ObjectId to string value in mongodb aggregate?
本文介绍了如何将$ 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"
}
}
}
])
这篇关于如何将$ project ObjectId转换为mongodb中的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文