Convert ObjectID to String in mongo Aggregation

后端 未结 5 1263
我在风中等你
我在风中等你 2021-02-05 12:15

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

{
  _id:ObjectId(\'56edbb4d5f084a51131dd4c6\'),
  userRef:ObjectId(\'56edbb4d5f084a51131dd4c6\'),
  seria         


        
5条回答
  •  天涯浪人
    2021-02-05 12:51

    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
    }
    

提交回复
热议问题