D
D
Denis11112019-07-15 12:27:41
MongoDB
Denis1111, 2019-07-15 12:27:41

Why is the first day of a month in ISOdate the last day of the previous month?

I am trying to do aggregation in mongoose. My task is to group documents (numbers) by months, and the problem is that for some reason mongodb puts the 1st day of the current month in the object of the previous one. That is, if there is a report for the 1st of this month, then in ISO format it is the 31st of the previous month, and this document should be included in the array of the current month, not the previous one. Same problem with the first day. month, which is grouped into the current month. I have to do checks all the time, which makes me uncomfortable. Are there any ways to solve this problem?

await Table.aggregate([
      {
        $match: {
          date: {$ne: null}
        }
      },
      {
        $group: {
          _id: {
            month: { $month: '$date' } 
          },
          doc: { $push: "$$ROOT" },
          count: { $sum: 1 }
        }
      },
      {
        $sort: {
          '_id.month': -1
        }
      }
    ]).exec();

output:
[ { _id: { month: 8 },
    doc: [ [Object], [Object], [Object], [Object], [Object] ],
    count: 5 },
  { _id: { month: 7 },
    doc:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    count: 31 },
  { _id: { month: 6 }, doc: [ [Object] ], count: 1 } ]

There shouldn't be 6 months, it's { _id: { month: 6 },
doc : [ [
Object ] ], count: 1 } the first document of the 7th month is the 1st of the next (8th month), which means that there should be 6, not 5 documents.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Buki, 2019-07-15
@alexbuki

Most likely, localization works, you need to set a timezone

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question