Convert ObjectID to String in mongo Aggregation
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'} ] },}