我有以下收藏,
Todos = {
username:{ type: String},
type: {type: String} // can be A | B
todos: [
title: {type: String},
createdAt: {type: String}
]
}
假设我有输入fromDate = "1-3-2019", toDate = "1-5-2019" and type = "A"
这应该会导致所有类型分别为3个月和4个月的用户的待办事项计数。]
我已经尝试过了。
const result = await Todos.aggregate([
{
$match: { type: 'A' }
},
{
$project: {
todos: {
$filter: {
input: '$todos',
as: 'todo',
cond: {
$and: [
{
$gte: [
{ $toDate: '$$todo.createdAt' },
{ $toDate: fromDate }
]
},
{
$lte: [
{ $toDate: '$$todo.createdAt' },
{ $toDate: toDate }
]
}
]
}
}
}
}
},
{ $group: { _id: '', count: { $sum: { $size: '$todos' } } } },
{ $project: { totalTodos: '$count' } }
])
但是这是我想要的结果,而不是2个计数的结果,第一个计数将给出3月的待办事项,第二个计数将给出4月的所有待办事项,因为在此输入日期之间有两个月的时间。
任何帮助将不胜感激,谢谢。
我修改了您的查询,以增加按createdAt
字段的月份数的步骤。请注意,本文中的所有日期字段均假定为dd-mm-yyyy
格式。
一些样本文件:
{ type: "A", todo: [ { title: "t1", createdAt: "1-3-2019" }, {title: "t2", createdAt: "12-8-2019"} ] },
{ type: "A", todo: [ { title: "t21", createdAt: "30-5-2019" }, {title: "t22", createdAt: "1-4-2019"} ] },
{ type: "A", todo: [ { title: "t90", createdAt: "26-3-2019" }, {title: "t92", createdAt: "19-9-2018"}, {title: "t99", createdAt: "1-5-2019"} ] }
查询:
var FROM_DATE = "1-3-2019"
var TO_DATE = "31-5-2019"
db.todos.aggregate( [
{
$match: { type: 'A' }
},
{
$project: {
todo: {
$filter: {
input: '$todo',
as: 'todo',
cond: {
$and: [
{
$gte: [
{ $toDate: '$$todo.createdAt' },
{ $toDate: FROM_DATE }
]
},
{
$lte: [
{ $toDate: '$$todo.createdAt' },
{ $toDate: TO_DATE }
]
}
]
}
}
}
}
},
{ $unwind: "$todo" },
{ $project: { createdAtMonth: { $month: { $toDate: "$todo.createdAt" } } } },
{ $group: { _id: "$createdAtMonth", countByMonth: { $sum: 1 } } },
{ $project: { createdAtMonth: "$_id", countByMonth: 1, _id: 0 } },
] )
输出:
{ "countByMonth" : 1, "createdAtMonth" : 4 }
{ "countByMonth" : 2, "createdAtMonth" : 5 }
{ "countByMonth" : 2, "createdAtMonth" : 3 }