Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - How to get top 10 customers with most turnover?

I would like to output the Top 10 customers with the most turnover.

So, I have a Order collection with this document input 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
}

I have already a solution, where I can output the total turnover from one specific customer. Here is an example:

//Get total turnover from this client
router.get('/admin/turnover/client/:userID', async (req, res) => {
  const userID = req.params.userID
  const mongoose = require("mongoose");
  let turnoverClient = await Order.aggregate([
    {
      $match: {"owner": new mongoose.Types.ObjectId(userID)}
    },
    {
      $group: {
        _id: '',
        "totalTurnover": { $sum: '$getCartTotalPrice'}
      }
    }
  ]).exec();

  const turnover = turnoverClient[0] || 0;

  if (turnover == 0) {
    const data = 0
    res.json(data)
  } else {
    const data = turnoverClient[0].totalTurnover.toLocaleString('de')
    res.json(data)
  }
});
question from:https://stackoverflow.com/questions/65901387/how-to-get-top-10-customers-with-most-turnover

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

1 Reply

0 votes
by (71.8m points)
  • $group by owner, get sum of getCartTotalPrice
  • $sort by totalTurnover descending order
  • $limit 10 documents
let Top10Clients = await Order.aggregate([
  {
    $group: {
      _id: "$owner",
      totalTurnover: { $sum: "$getCartTotalPrice" }
    }
  },
  { $sort: { totalTurnover: -1 } },
  { $limit: 10 }
]);

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...