mongodb聚合项目objectId与concat

2024-02-18

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

avatar 返回 null,可能是因为它的 objectId,在这个查询中是否可以从这个 objectId 字符串中生成?


从 MongoDB 4.0 及更高版本开始,有一个$toString https://docs.mongodb.com/manual/reference/operator/aggregation/toString/#exp._S_toString返回的运算符ObjectId十六进制字符串形式的值:

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

或使用$convert https://docs.mongodb.com/manual/reference/operator/aggregation/convert/#convert-to-objectid

db.test.aggregate([
    { "$match": { 
        "themType": "SuperTest", 
        "mType": { "$in" : [1 , 2] }
    } },
    { "$addFields": { 
        "avatar": { 
            "$convert": { "input": "$refTestId", "to": "string" }
        }
    } }
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mongodb聚合项目objectId与concat 的相关文章

随机推荐