是否可以在查询聚合中获取当月、季度和半年的销售额总和,或者我单独执行每个查询?
无论模型如何,我的问题是您是否可以在单个查询中获取所有信息,还是应该单独进行。
如果没有,获取此信息的最佳方式是什么?
最佳答案
根据文档字段的具体情况,这可以通过聚合框架使用 match
、project
和 group
的组合来完成> 阶段。
作为示例,我将假设一个 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/