【发布时间】:2023-04-03 16:13:01
【问题描述】:
我在 mongodb 中的集合如下所示:
发帖:
// ...
tags: [
{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag',
required: true,
}
// ...
}
],
date: {
type: Date,
}
// ...
我想写一个查询结果如下:
[
{
"month": "Jan",
"tag1": 5,
"tag2": 80,
// ...
},
{
"month": "Feb",
"tag1": 30,
"tag2": 95,
// ...
},
// ...
]
我想我需要使用聚合。对吗?
我写了这个,但结果不是我想要的。
const monthStrings = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Posst.aggregate([
{
$match: {
$expr: {
$and: [
{ $gt: ["$created_at", oneYearFromNow] },
{ $lt: ["$created_at", dateNow] }
],
}
}
},
{
$group: {
_id: {
month: { $month: "$date" },
year: { $year: "$date" },
},
count: {
$sum: 1
}
}
},
{
$project: {
_id: {
$concat: [
{
$arrayElemAt: [
monthStrings,
"$_id.month"
]
},
"-",
"$_id.year"
]
},
count: 1,
}
}
])
我怎样才能得到我想要的结果?
(返回的格式并不重要,但我想要实现的是在单个查询中检索同一分组的多个计数(每月一个)。)
【问题讨论】:
-
你试过什么?添加您的另一个架构并为集合添加示例文档并从该文档中添加预期结果。
-
请检查我的编辑。 @turivishal
-
如果您添加一些示例文档会有所帮助。
-
可能类似于下面的答案,如果这有帮助mongoplayground.net/p/RPK4X_3C-ru
标签: node.js mongodb mongoose aggregation-framework