Kaherdin
Kaherdin

Reputation: 2127

Mongodb : Concat Month and Year

I'm using a aggregation to determine the month when a user is connecting to my platform.

For that, I've got this aggregation :

 { 
        "$project" : {
          cuid: 1, username: 1, creationDate: 1, language: 1, favorites: 1, active: 1, company: { cuid: 1, name: 1, logoUrl: 1, type: 1 }, connectionLog: 1,
      profile: { $cond: ['$active', '$profile', null] },
            "connectionMonth" : {
                "$cond" : [
                    {
                        "$ifNull" : [
                            "$connectionLog", 
                            0.0
                        ]
                    }, 
                    {
                         $month: "$connectionLog" 
                    }, 
                    -1.0
                ]
            }, 

        }
    }, 

And it's working as expected, only problem, I want to have out connectionMonth output the Month + Year. Something like 07.2019 will be great. I try to concat but it didn't work.

Upvotes: 1

Views: 682

Answers (1)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

We first need to convert the month and year into a string. The following query can get us the expected output:

db.collection.aggregate([
    {
        $project:{
            "connectionMonth":{
                $concat:[
                    {
                        $toString:{
                            $month:"$connectionLog"
                        }
                    },
                    ".",
                    {
                        $toString:{
                            $year:"$connectionLog"
                        }
                    }
                ]
            }
        }
    }
]).pretty()

Second approach:

db.collection.aggregate([
    {
        $project:{
            "connectionMonth":{ 
                "$dateToString": {
                    "date": "$connectionLog",
                    "format": "%m.%Y",
                } 
            }
        }
    }
]).pretty()

Upvotes: 1

Related Questions