我知道这里有这个问题的其他版本,但我正在努力让这个问题保持一致.我有类似以下内容的文档:
[
{_id: 1, date: "2022-04-08T23:30:12.000Z", books: [{author: "Johnson", title: "First Title"}, {author: "Smith", title: "Second Title}]},
{_id: 2, date: "2022-04-22T23:30:12.000Z", books: [{author: "Johnson", title: "Some Other Title"}]},
{_id: 3, date: "2022-05-05T23:30:12.000Z", books: [{author: "Smith", title: "Title Round 2"}]},
{_id: 4, date: "2022-05-15T23:30:12.000Z", books: [{author: "Johnson", title: "Found a Title", {author: "Smith", title: "Wrote again"}, {author: "Brooks", title: "New Title"}]}
]
我try 按月-年对文档进行分组,然后计算不同值显示在作者字段上的次数.到目前为止,我有一个管道,看起来像:
{
"$unwind": "$books"
},
{
$project: {
_id: 1,
books: 1,
month: {
"$month": "$date"
},
year: {
"$year": "$date"
}
}
},
{
$project: {
_id: 1,
books: 1,
date: {
$concat: [
{
$substr: [
"$year",
0,
4
]
},
"-",
{
$substr: [
"$month",
0,
2
]
},
]
}
}
},
{
$group: {
_id: {
date: "$date",
books: {
freq: {
$sum: 1
}
}
}
}
},
{
$project: {
"_id": 1,
"date": 1,
"books": 1
}
},
]
}
我的目标是最终输出如下所示:
[
{date: "2022-04", authors: { "Johnson": 2, "Smith": 1}},
{date: "2022-05", authors: {"Johnson": 1, "Smith": 2, "Brooks": 1}}
]
我已经找到了对子文档运行计数的方法,但在try 实现时,我正在丢失按日期分组的方法,或者只是得到错误.我已经看得够多了,知道它是可行的,只是在试图把它做得恰到好处时迷失了方向.如有任何帮助,我们不胜感激.