Why aggregate ($date) method is not working in MongoDB

252 views Asked by At

Why below code works

 db.getCollection('CustomerData').aggregate([       
    {$addFields: {
        "month": {$month: new Date("2018-09-18T00:00:00.000Z")},       
        "year": {$year: new Date("2018-09-18T00:00:00.000Z")}
         }
    },
    {$match: { month: 9, year: 2018, flag: 'dealer' } }
])

But not this

 db.getCollection('CustomerData').aggregate([       
    {$addFields: {
        "month": {$month: new Date("$date")},       
        "year": {$year: new Date("$date")}
         }
    },
    {$match: { month: 9, year: 2018, flag: 'dealer' } }
])

Note: In document there is date field. i am using MongoClient. sample data.

{
"_id" : ObjectId("5b9ed3f221f0c70c7c0fd035"),
"customerName" : "aaa",    
"date" : "2018-09-18T00:00:00.000Z",    
"flag" : "dealer"
}
1

There are 1 answers

0
s7vr On

The correct mongodb operator is $dateFromString.

db.getCollection('CustomerData').aggregate([       
    {$addFields:{
        "month":{$month:{$dateFromString:{
    dateString:"$date"}}},
        "year":{$year:{$dateFromString:{
    dateString:"$date"}}}
    }},
    {$match:{month:9,year:2018,flag:'dealer'}}
])

You can do aggregation pipeline in regular query in 3.6. I will add that too.