Home > Software design >  Is there any aggregation function to get weekday or month as string in mongodb?
Is there any aggregation function to get weekday or month as string in mongodb?

Time:12-07

Basically I want to get weekday and month values as string in mongodb, I found $dayOfWeek and $month functions under $project and they return integer values, how can I convert these integers to string?

For example in sql-server, I can get day and month as string like the following:

DECLARE @date datetime = '2019-11-11T13:28:22.300';   
SELECT DATENAME(WEEKDAY, @date) as weekday, DATENAME(month, @date) as month;

In mongodb, I have tried the following aggregation:

data:

_id: ObjectId('6384b63e48c7aa84d66ec31f') timestamp: 2019-11-11T13:28:22.300 00:00

then I created the following aggregation:

[
  {
    '$project': {
      '_id': 0, 
      'weekday': {
        '$dayOfWeek': '$timestamp'
      }, 
      'month': {
        '$month': '$timestamp'
      }
    }
  }
]

and the result is:

weekday: 2 month: 11

CodePudding user response:

Instead of switch-case, you can use $arrayElemAt to write it concisely.

[
  {
    '$project': {
      '_id': 0, 
      'weekday': {
        $arrayElemAt: [['','Sun','Mon','Tue','Wed','Thu','Fri','Sat'], {'$dayOfWeek': '$timestamp'}]        
      }, 
      'month': {
        $arrayElemAt: [['','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], {'$month': '$timestamp'}]
      }
    }
  }
]
  • Related