Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregation project objectId with concat

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

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

like image 949
FrancMo Avatar asked Sep 29 '14 20:09

FrancMo


2 Answers

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" }
    } }
])

or using $convert

db.test.aggregate([
    { "$match": { 
        "themType": "SuperTest", 
        "mType": { "$in" : [1 , 2] }
    } },
    { "$addFields": { 
        "avatar": { 
            "$convert": { "input": "$refTestId", "to": "string" }
        }
    } }
])
like image 199
chridam Avatar answered Oct 03 '22 18:10

chridam


This isn't possible yet. WiP issue see: https://jira.mongodb.org/browse/SERVER-29512

like image 22
A T Avatar answered Oct 03 '22 16:10

A T