Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

mongodb - Get total turnover from current year --- not from last 365 days

I would like to output the total turnover of all orders only from the current year. The current year should be dynamically. It's important that the year will be updated automatically.

In the moment I can only output the turnover from the last 365 days.

let year = await Order.aggregate([
    {$match : {"createdAt":{"$gt":new Date(Date.now() - 24*60*60*365 * 1000)}}},
    
    {
      $group: {
        _id: '',
        "totalYear": { $sum:  '$getCartTotalPrice' }
      }
    }
  ]).exec();

console.log(year)

Document example:

{
  _id: ObjectId()
  products: Array
  getCartTotalPrice: 100
  owner: ObjectId()
  createdAt: 2020-10-21T14:24:17.918+00:00
  updatedAt: 2020-10-21T14:24:17.918+00:00
  __v: 0
}

Expected output: Sum of 'getCartTotalPrice' from all documents from current year (2021 e.g.)

question from:https://stackoverflow.com/questions/65892578/get-total-turnover-from-current-year-not-from-last-365-days

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 {$match : {"createdAt":{"$gt":new Date(new Date().getFullYear(),0,1,0,59,59,999).toJSON()    }}}

Here is output from the js function:

 mongos> new Date(new Date().getFullYear(),0,1,0,59,59,999).toJSON()
 2020-12-31T23:59:59.999Z
 mongos> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...