为什么聚合($ date)方法在MongoDB中不起作用

时间:2018-09-16 23:01:23

标签: node.js mongodb mongodb-query mongodate

以下代码为何起作用

 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' } }
])

但不是这个

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

注意:文档中有日期字段。我正在使用MongoClient。样本数据。

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

1 个答案:

答案 0 :(得分:1)

正确的mongodb运算符为$dateFromString

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

您可以在3.6中的常规查询中执行聚合管道。我也将添加。