16

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.

Ashh
  • 36,647
  • 11
  • 71
  • 96
André Perazzi
  • 999
  • 1
  • 10
  • 26

5 Answers5

7

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

Ashh
  • 36,647
  • 11
  • 71
  • 96
6

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'
    }
);
Pang
  • 8,605
  • 144
  • 77
  • 113
André Perazzi
  • 999
  • 1
  • 10
  • 26
2

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

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

I think you may try to resolve it by using an Array which contains both fields:

{$project:{newkey:['$userRef','$serialNumber']},{$match:{newkey:{$in:filterArray}}}}

this may match the data with both fields to the filter. Please notice that the data in the newkey array should have the same data type with the filterArray elements.

John.H
  • 46
  • 1
-2

You can use $substr https://docs.mongodb.com/manual/reference/operator/aggregation/substr/#exp._S_substr to cast any object to string before $concat.

This is a sample of code that's working for me.

group_id_i['_id'] = {
    '$concat' => [
        { '$substr' => [ {'$year' => '$t'}, 0, -1] }, '-',
        { '$substr' => [ {'$month' => '$t'}, 0, -1] }, '-',
        { '$substr' => [ {'$dayOfMonth' => '$t'}, 0, -1] }
    ]
} 

Where t is DateTime field, this aggregation returns data like so.

{
    "_id" => "28-9-2016",
    "i" => 2
}
Alexis Tyler
  • 1,515
  • 6
  • 26
  • 44
aminhotob
  • 1,006
  • 14
  • 16