如何 $project ObjectId 到 mongodb 聚合中的字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36059986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to $project ObjectId to string value in mongodb aggregate?
提问by matus
Is there an operator I could use in aggregatefunction to get a string instead of ObjectId in response?
是否有我可以在聚合函数中使用的运算符来获取字符串而不是 ObjectId 作为响应?
db.something.aggregate([
{ "$match": { "property": { "$exists": true } } },
{ "$project": { "stringId": "$_id.???" } }
])
回答by Ashh
Mongodb 4.0has introduced $toString
aggregation operator. So, Now you can easily convert ObjectId to string
Mongodb 4.0引入了$toString
聚合操作符。所以,现在您可以轻松地将 ObjectId 转换为字符串
db.collection.aggregate([
{
$project: {
_id: {
$toString: "$_id"
}
}
}
])
OR vice versa using $toObjectId
aggregation
或反之亦然使用$toObjectId
聚合
db.collection.aggregate([
{
$project: {
_id: {
$toObjectId: "$_id"
}
}
}
])
回答by Tamil Arasi
There is no Direct Operator in aggregate function to get String from ObjectId.
聚合函数中没有直接运算符来从 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()
.
在 2.6 版之后,您可以使用ObjectId.toString()
方法将 ObjectId 转换为字符串。首先匹配并投影 ObjectID。然后,您可以使用 将此对象 ID 转换为字符串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()
然后使用结果对象并使用获取字符串作为响应 ObjectID.tostring()
Edit: You can access the str attribute of the object id using
编辑:您可以使用访问对象 id 的 str 属性
ObjectId("507f191e810c19729de860ea").str
source: mongodb docs
来源:mongodb 文档
回答by user1260158
You can do it inline using the $concat
operator:
您可以使用$concat
运算符进行内联:
db.something.aggregate(
[
{ $match :
{ 'property' :
{ $exists:true }
}
},
{ $project:
{ stringId:
{ $concat: [ ObjectId().str ] }
}
}
]
)