Convert ObjectID to String in mongo Aggregation Convert ObjectID to String in mongo Aggregation mongoose mongoose

Convert ObjectID to String in mongo Aggregation


Now you can try with $toString aggregation which simply converts ObjectId to string

db.collection.aggregate([    { "$addFields": {        "userRef": { "$toString": "$userRef" }    }},    { "$group": {      "_id": { "$concat": ["$userRef", "-", "$serialNumber"] }    }}])

You can check the output here


I couldn't find a way to do what I wanted, so instead, I created a MapReduce function that, in the end, generated the keys the way I wanted to (concatenating other keys).

At the end, it looked something like this:

db.collection('myCollection').mapReduce(    function() {        emit(            this.userRef.str + '-' + this.serialNumber , {                count: 1,                whateverValue1:this.value1,                whateverValue2:this.value2,                ...            }        )    },    function(key, values) {       var reduce = {}       .... my reduce function....        return reduce    }, {        query: {            ...filters_here....        },        out: 'name_of_output_collection'    });


You can simply use $toString to apply $concat in aggregation on ObjectIDs in the following way -

$group: {    '_id': {        '$concat': [            { '$toString' : '$userRef' },            '-',            { '$toString' : '$serialNumber'}        ]    },}