node.js - mongodb可以查询当月、季度、学期的销售额吗?

标签 node.js mongodb mongoose aggregation-framework

是否可以在查询聚合中获取当月、季度和半年的销售额总和,或者我单独执行每个查询?

无论模型如何,我的问题是您是否可以在单个查询中获取所有信息,还是应该单独进行。

如果没有,获取此信息的最佳方式是什么?

最佳答案

根据文档字段的具体情况,这可以通过聚合框架使用 matchprojectgroup 的组合来完成> 阶段。

作为示例,我将假设一个 Sales 文档,其中包含 date 字段和 amount 字段,应将其聚合为获取给定期间的总销售额(还需要事先定义月份、季度和半个条件的相应日期变量,例如从服务器 GET 请求中包含的查询参数)

Sales.aggregate()
.match(...include general non-date matches here, e.g. company, etc.)  
.project({
   'month': {
      '$cond': { if: {
         '$and': [
            { $gte: [ 'date', new Date(monthStartDate) ] },                
            { $lte: [ 'date', new Date(monthEndDate) ] },
         ]}, then: 'amount', else: 0
       } 
    },
    'quarter': {
      '$cond': { if: {
         '$and': [
            { $gte: [ 'date', new Date(quarterStartDate) ] },                
            { $lte: [ 'date', new Date(quarterEndDate) ] },
         ]}, then: 'amount', else: 0
       } 
    },
    'half': {
      '$cond': { if: {
         '$and': [
            { $gte: [ 'date', new Date(halfStartDate) ] },                
            { $lte: [ 'date', new Date(halfEndDate) ] },
         ]}, then: 'amount', else: 0
       } 
     }
})
.group({
   _id: '_id',
   month: { $sum: '$month' },
   quarter: { $sum: '$quarter' },
   half: { $sum: '$half' }
})
.exec(function(err, res) {
   if (err) { reject(err) }
   resolve(res)
})

关于node.js - mongodb可以查询当月、季度、学期的销售额吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680806/

相关文章:

node.js - 如何在分组后对数组值进行排序 - mongodb

Mongoose 身份验证异常

node.js - ECMAScript 2015 (ES6) 在 Node JS 上不带标志

javascript - 在 JavaScript 中获取 API 以将表单数据保存到 JSON 或文本文件

Python:关于打包应用程序 docker vs pyinstaller 的问题

mysql - Node.js脚本过早退出

node.js - 创建后如何在 mongoose 中填充子文档?

javascript - Mongoose 保存请求正文中的所有参数

javascript - 如何在EJS中包含内容?

javascript - Kubernetes 替换部署失败