MongoDB 聚合统计

聚合(aggregate)主要用于计算数据,类似sql中的sum(),avg()。


db.集合名称.aggregate({管道:{表达式}})

?管道
?
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的输入 在mongodb中,管道具有同样的作用,文档处理完毕后,通过管道进行下一次处理 常用管道
  • $group:将集合中的文档分组,可用于统计结果
  • $match:过滤数据,只输出符合条件的文档
  • $project:修改输入文档的结构,如重命名、增加、删除字段、创建计算结果
  • $sort:将输入文档排序后输出
  • $limit:限制聚合管道返回的文档数
  • $skip:跳过指定数量的文档,并返回余下的文档
  • $unwind:将数组类型的字段进行拆分

?
?
表达式
?
处理输入文档并输出
?
$sum:计算总和?
$avg:计算平均值?
$min:获取最小值?
$max:获取最大值?
$push:在结果文档中插入值到一个数组中?
$first:根据资源文档的排序获取第一个文档数据?
$last:根据资源文档的排序获取最后一个文档数据?
例子
表结构:
 const compAccountDealrecordSchema = new Schema({
// billing 订单标识
numer: {
type: String
},
// 公司名称
_comp: {
type: Schema.Types.ObjectId,
ref: 'Company',
required: true,
index: true
},
// 消费金额
amount: {
type: Number,
default: 0.00
},
// 账户余额
balance: {
type: Number,
default: 0.00
},
// 渠道类型
channelType: {
type: String,
default: 'BALANCE'
},
// 日账单
dailyBill: {
type: Boolean,
default: false
},
// 按需扣费账单
debtDeduct: {
type: Boolean,
default: false
},
// 描述
detail: {
type: String,
default: ''
},
// 账单
detailRequest: {
type: Schema.Types.ObjectId,
ref: 'Company',
},
// 账单类型
detailType: {
type: String,
default: 'LINK'
},
// 账单链接
detailUrl: {
type: String,
default: ''
},
// 订单ID
orderId: {
type: Schema.Types.ObjectId,
ref: 'comp_account_billing_order'
},
// 账单产品详细
serviceItem: [],
// 产品类型
serviceType: {},
// 交易类型 [RECHARGE:收入,CONSUME:支出]
transactionType: {
type: String,
default: 'CONSUME'
},
// 备注
remark: {

}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
});
静态方法
    compAccountDealrecordSchema.statics = {
getAll: async function(queryMix, _comp) {
const {
querys,
select
} = queryMix;
const models = this.find({
...!!_comp && {
_comp
}
})
.sort({
'_id': -1,
});
try {
return {
data: {
result: await models,
totalCount: await models.count()
}
};
} catch (error) {
return error
}
},
getOne: async function(_id, _comp) {
const MODELS = this.findOne({..._comp && {
_comp
},
_id
}).sort({
'_id': -1
});
try {
return {
data: await MODELS
}
} catch (error) {
return error
}
},
createOne: async function(bodys) {
return await this.create(bodys)
},
backCashAdd: async function(bodys, auth) {
const {
_comp,
serviceBillCash,
serviceBillChannel,
serviceBillRemark
} = bodys
// 生成流水
await this.create({
'_comp': _comp,
'serviceBillProduct': '-',
'serviceBillType': '充值',
'serviceBillCash': `+${serviceBillCash}`,
'serviceBillChannel': `${serviceBillChannel}`,
'serviceBillRemark': `手工入款/n${serviceBillChannel}/n${serviceBillRemark}`,
'_admin': auth.id
});
return await ctx.model.Company.cashFN(serviceBillCash, auth, 'cash', 'add', _comp);
},
seachComp: async function(name) {
return await ctx.model.Company.find({
'compName': eval(`/${name}.*/i`)
}, {
'compEmail': 1,
'compName': 1,
'compPhone': 1
})
},
// 图表数据
/**
*
* @param {*} type 订单类型
* @param {*} scope 月份计算
* @param {*} _comp
*/
getPanelChart: async function(type = 'all', classify = "line", _comp) {
const MODEL = this.aggregate([
...classify === 'pie' ? [{
$unwind: `$serviceItem`,
}] : [],
...[{
$match: {
'_comp': mongoose.Types.ObjectId(_comp),
'created': {
"$gt": new Date(subtractMoment(1, 'month'))
},
"channelType": "CASH",
...type !== 'all' && {
'serviceItem.serviceType': type
}
}
},
{
$project: {
'_comp': 1,
'amount': 1,
'created': 1,
"serviceItem": 1,
'day': {
$substr: ["$created", 0, 10]
}
}
},
{
$group: {
...classify === "line" ? {
'_id': `$day`
} : {
'_id': '$serviceItem.serviceType'
},
'count': {
$sum: classify === 'pie' ? '$serviceItem.price' : '$amount'
}
}
},
{
$project: {
...classify === "line" ? {
'days': '$_id'
} : {
'serviceType': '$_id'
},
'count': 1,
_id: 0
}
},
{
$sort: {
'days': 1
}
}
]
]);
try {
const lastMonth = subtractMoment(1, 'month', 'subtract');
const DateMaps = (getDayAll(lastMonth, new Date()));
const data = await MODEL;
return {
...classify === 'pie' ? {
data
} : {
'data': {
datas: DateMaps.reduce((a, b) => {
let count;
data.forEach(e => {
if (e.days === b) count = e.count
});
a.push(count ? count : 0);
return a
}, []),
dates: DateMaps
}
}
}
} catch (error) {
console.log(error)
}
},
/**
* @param {String} type 产品类型()
*/
getCashCount: async function(ctx, auth, type, _comp) {
const {
endDate
} = ctx.helper.getPrevMoment('month');
const yestoday = ctx.helper.subtractMoment(1, 'day');
const typeoObj = type === 'all' ? {} : {
'serviceBillProduct': type,
'_comp': mongoose.Types.ObjectId(_comp ? _comp : auth.id)
};
return [(await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(endDate)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'monthCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
}
]))[0], (await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(yestoday)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'dayCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
},
]))[0]]
},
};

0 个评论

要回复文章请先登录注册