Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ObjectID to String in mongo Aggregation

I'm in this scenario right now: I have a collection X:

{
  _id:ObjectId('56edbb4d5f084a51131dd4c6'),
  userRef:ObjectId('56edbb4d5f084a51131dd4c6'),
  serialNumber:'A123123',
  ...
}

I need to aggregate all documents, grouping them by the userRef + serialNumber, so I'm trying to use concat like this:

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

So basically in my aggregation in MongoDB, I need to group documents by the concatenation of a ObjectId and a string. However, It seems that $concat only accepts strings as parameters:

uncaught exception: aggregate failed: {

    "errmsg" : "exception: $concat only supports strings, not OID",
    "code" : 16702,
    "ok" : 0
}

Is there a way to convert an ObjectId to a String within an aggregation expression?

EDIT:

This question is related, but I the solution doesn't fit my problem. (Specially because I can't use ObjectId.toString() during the aggregation)

Indeed I couldn't find any ObjectId().toString() operation in Mongo's documentation, but I wonder if there's any tricky thing that can be done in this case.

like image 944
André Perazzi Avatar asked May 26 '16 20:05

André Perazzi


1 Answers

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

like image 51
Ashh Avatar answered Oct 02 '22 19:10

Ashh