带有concat的mongodb聚合项目objectId [英] mongodb aggregation project objectId with concat

查看:340
本文介绍了带有concat的mongodb聚合项目objectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

db.test.aggregate({
    $match : { "themType" : "SuperTest" , "mType" : { "$in" : [ 1 , 2]}}
}, 
{ $project : { "_id" : 1, "refTestId" : 1, "avatar" : { $concat : [$refTestId] }
  } });

并且化身向我返回null,可能是因为它的objectId,在此查询中是否有可能从此objectId字符串中得出?

and avatar returns me null, probably its because its objectId, is it possible in this query to make from this objectId string ?

推荐答案

从MongoDB 4.0及更高版本开始,有一个

From MongoDB 4.0 and newer, there is a $toString operator which returns the ObjectId value as a hexadecimal string:

db.test.aggregate([
    { "$match": { 
        "themType": "SuperTest", 
        "mType": { "$in" : [1 , 2] }
    } },
    { "$addFields": { 
        "avatar": { "$toString": "$refTestId" }
    } }
])

或使用 $convert

db.test.aggregate([
    { "$match": { 
        "themType": "SuperTest", 
        "mType": { "$in" : [1 , 2] }
    } },
    { "$addFields": { 
        "avatar": { 
            "$convert": { "input": "$refTestId", "to": "string" }
        }
    } }
])

这篇关于带有concat的mongodb聚合项目objectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆