我的要求是让特定用户获得根据月分组的所有费用,并返回月和该月的总费用。 我有如下收藏。
expenses = {{
"_id": {
"$oid": "5bc0f74df46dae0bf4ffdc39"
},
"user": {
"$oid": "5bab847a5b0d2e2ce8b4cbe5"
},
"date": "15-Mar-2018",
"expenseInfo": "Clothes",
"category": "Shopping",
"amount": 100,
"__v": 0
},
{
"_id": {
"$oid": "5bc0f78bf46dae0bf4ffdc3b"
},
"user": {
"$oid": "5bab847a5b0d2e2ce8b4cbe5"
},
"date": "11-Apr-2018",
"expenseInfo": "mobile",
"category": "Bills",
"amount": 100,
"__v": 0
},
{
"_id": {
"$oid": "5bc0f76cf46dae0bf4ffdc3a"
},
"user": {
"$oid": "5bab847a5b0d2e2ce8b4cbe5"
},
"date": "18-Apr-2018",
"expenseInfo": "Petrol",
"category": "Fuel",
"amount": 20,
"__v": 0
}
}
这是我的费用模式。 另外,请注意,用户对象(用户是费用模式中引用的其他模式)
const ExpenseSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
date: {
type: String
},
expenseInfo: {
type: String,
required: true
},
category: {
type: String,
required: true
},
amount: {
type: Number,
required: true
}
});
我尝试过类似的操作,但是没有任何数据。这是什么问题?
Expense.aggregate([{
$match: {
"_id": request.user.id
}
},
{
"$group": {
"_id": {
"$arrayElemAt": [{
"$split": ["$date", "-"]
}, 1]
},
"Total": {
"$sum": "$amount"
}
}
}
])