How can I manipulate a date field in an aggregation pipeline?

筅森魡賤 提交于 2020-04-07 10:30:45

问题


I'm trying to set the time from a Date field to the start of the day

function getDate(date){ return new Date(date.getYear(), date.getMonth(), 
date.getDate(), 0,0,0); }
...
{"$project" : {
    "_id"   : getDate("$dt"),
...
  • If I send "$dt" I get TypeError: date.getYear is not a function as I'm passing a string,

  • If remove the quotation marks, I get Error: "$dt is not defined",

  • but if I set "$dt" as value for "_id" I get a correct ISO Date.

So how do I pass the date object to the function?


回答1:


MongoDB's aggregation pipeline does not support JavaScript. To manipulate date values for results in the aggregation pipeline you need to use Date Aggregation Operators.

For example :

db.date.aggregate([
    { $project: {
         _id: { $dateToString: { format: "%Y%m%d", date: "$dt" }}
    }}
])

Assuming you have a document with a field called dt with a date value of ISODate("2017-07-01T10:01:23.344Z"), the result would look like:

{
  "result": [

    {
      "_id": "20170701"
    }

  ],
  "ok": 1
}

Note: if you have multiple documents for the same day, this approach will create duplicate _id values in your results. You may want to project to a different field name or perhaps use a $group stage instead of $project if your intent is to combine values for the same day.



来源:https://stackoverflow.com/questions/44858270/how-can-i-manipulate-a-date-field-in-an-aggregation-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!