Convert ObjectID to String in mongo Aggregation

感情迁移 提交于 2019-12-03 06:08:08
André Perazzi

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'
    }
);

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 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.

aminhotob

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!