Q:

mongodb: $substr inside $group

I am a bit new to mongodb, and I have a situation.
The entries in my mongodb collection is around 300k, I used mongodb aggregate to migrate all the old entries to new and my code looks like
collection.aggregate([
  { $group: {
    _id: "$_id",
    "new_id" : {$substr : [{$first: "$old_id"}, 2,-1]}, //error exists here
    "new_roles": {$push: "$old_role"},
    }
  },
   { $out: newCollection}
], {allowDiskUse:true}, function (updateError, updateResult) {
  if (!updateError) {
    return cb(false, true);
  } else {
    return cb(true, false);
  }
})

What I want to achieve it that I want to take substring of old_id and put it in new_id. The old_id of old collection looks like a-112 a-34311. I want to remove a- from these old ids and put it into new id.
I tried using the above code but it shows error that The $substr accumulator is a unary operator. I tried searching for the error but no luck

A:

You can't use $substr in the $group stage as it is not an accumulator operator. You need to do this in a $project stage like this:
collection.aggregate([
  { $group: {
    _id: "$_id",
    "new_id" : {$first: "$old_id"},
    "new_roles": {$push: "$old_role"},
    }
  },
   {$project: { 
      "new_id": {$substr: ["$new_id", 2, -1]}, 
      "new_roles": 1
     }
   }, 
   { $out: newCollection}
], {allowDiskUse:true}, function (updateError, updateResult) {
  if (!updateError) {
    return cb(false, true);
  } else {
    return cb(true, false);
  }
})

