0

date was save in below format using moment.

 let date= moment().format('MMMM Do YYYY, h:mm:ss a');

When i try to get the year by using below code. I am getting Undefined as output

db.checkouts.aggregate(
    {"$project":{  date:1,
              "year":{"$year":"$date"},
       total:1,
       delivered:1,
       count:1,
       clientName:1,
       clientId:1,
       dealerId:1
    }},{"$match":{
       dealerId:status.UserNumber
    }},function(err,o){
        console.log(o);
        if(o) callback(o);
    }

)

Can I get the year from this date format?

karthik
  • 35
  • 7

1 Answers1

1

$year and $month are valid with date types only.

Change your type to date to use the above expressions.

Or

You can use $substr to extract Year and Month for string date value.

$project: {year:{$substr:["$date", 8, 4]}, month:{$substr:["$date", 0, 4]}
s7vr
  • 73,656
  • 11
  • 106
  • 127