我有一个user_status集合,它的架构是这样的
const userStatus = mongoose.model(
'user_status',
new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'user'
},
isActive: {
type: Boolean,
default: false
}
},
{ timestamps: true }
)
);
我需要获取给定特定月份(1、2等的所有活跃用户的数量)
我尝试过了。但是此代码片段并未提供预期的输出
// get all active user count for a specific month
router.post('/report', async (req, res) => {
const selectedMonth = req.body.month;
console.log('month', selectedMonth);
const usersStatus = await UserStatus.aggregate([
{ $project: { month: { $month: '$updatedAt' } } },
{
$match: { $and: [{ month: { $eq: selectedMonth } }, { isActive: true }] }
},
{ $group: { _id: '$user', count: { $sum: 1 } } }
]).exec();
res.status(200).send(usersStatus);
});
你能告诉我哪里错了吗?
答案 0 :(得分:1)
在第一个$project
阶段之后,您已经消失了isActive
和user
字段
您可以使用以下汇总
const usersStatus = await UserStatus.aggregate([
{ "$addFields": { "month": { "$month": "$updatedAt" } } },
{ "$match": { "month": selectedMonth, "isActive": true }},
{ "$group": { "_id": "$user", "count": { "$sum": 1 } } }
])
或更简单的使用$expr
const usersStatus = await UserStatus.aggregate([
{ "$match": {
"$expr": {
"$and": [
{ "$eq": [{ "$month": "$updatedAt" }, selectedMonth] },
{ "$eq": ["$isActive", true] }
]
}
}},
{ "$group": { "_id": "$user", "count": { "$sum": 1 } } }
])