如何在组查询中正确使用toDate

时间:2019-03-22 00:34:20

标签: mongodb

我正在处理一个查询,该查询每天将记录分组并在MongoDB上对它们进行计数 这是我的查询

db.getCollection('CustomerApplications').aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: { $toDate: "$data.submittedAt" }}, year: { $year: { $toDate: "$data.submittedAt" } } },
           count: { $sum: 1 }
         }
     }
   ]
)

$ data.submittedAt是一个双精度型,因此我需要将其转换为日期,然后从中拉出$ dayOfYear 但我得到

  

无法识别的表达式'$ toDate'

我的数据结构就像

{
    "_id" : ObjectId("5c942f50dae240feb1942b00"),
    "data" : {
        "id" : "624c0d17-b683-4c89-9d7c-011577d4e3b8",
        "email" : "i8888@eee.com",
        "name" : "ianh",
        "phoneNumber" : "+1222222",
        "score" : 12,
        "status" : "PENDING",
        "submittedAt" : 1553215312006.0,
        "surveyVersion" : "1"
    },
    "updatedAt" : ISODate("2019-03-21T00:41:52.192Z")
}

如果是的话,在MongoDB中这是否可行?

1 个答案:

答案 0 :(得分:0)

$toDate New in version 4.0. Please check your version

可以尝试一下吗?

db.getCollection('CustomerApplications').aggregate(
[
 {
   $group:
     {
      _id : { $substr: ["$data.submittedAt", 0, 10] },
       count: { $sum: 1 }
     }
 }
])    

希望这对您有帮助

$toDate - Converts a value to a date (New in version 4.0)

$dayOfMonth - Returns the day of the month for a date as a number between 1 and 31

$dayOfYear - Returns the day of the year for a date as a number between 1 and 366