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

前端 未结 1 1716
醉梦人生
醉梦人生 2021-01-29 07:56

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         


        
相关标签:
1条回答
  • 2021-01-29 08:13

    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.

    0 讨论(0)
提交回复
热议问题