【发布时间】:2021-12-17 07:13:53
【问题描述】:
我正在努力了解 MongoDB 以及聚合和组。到目前为止,我已经花了大约 3 天时间。
我的源数据看起来像...
{
"formName" : "my form",
"updatedAt" : "2021-11-02T13:29:00.123Z",
},
{
"formName" : "another form",
"lastUpdated" : "2021-10-01T13:29:00.123123",
},
请注意,可能有不同的日期名称,尽管这些是唯一的区别。
我正在尝试实现...的输出
{
"_id": null,
"text": "my form", (NOTE: This is the formName)
"children": [{
"text" : 2021, (This is the year part of the updated)
"children" : [
{"text" : 1}, (These are the month part of the updated)
{"text" : 2},
{"text" : 3},
{"text" : 4}
]
},
]
}
所以,基本上是一棵树,它有 formName,子分支是年,子分支是月。
各种方法我都试过了,很多都不行,比如嵌套在$groups里面的$addToSet。
我已经接近了,但我解决不了。
这是最接近的,但这不起作用。
db.FormsStore.aggregate( [
{$match:{myKey:"a guid to group my forms together"}},
{$project: {formName:1, lastUpdated:1, updatedAt:1}},
{
$group: {
_id: { formName: "$formName" },
Year: {$addToSet: {$year: {$dateFromString: { dateString: "$lastUpdated" }}}},
Month: {$addToSet: {$month: {$dateFromString: { dateString: "$lastUpdated" }}}},
}
},
{
$group: {
_id: { formName: "$_id.formName" },
Time: {$addToSet: {year: "$Year", month: "$Month"}}
}
}
]
)
输出显示...
{
_id: { formName: 'One of my forms' },
Time: [
{
year: [ 2021 ],
month: [ 10, 11 ]
}
]
}
这将全部用在 C# 中
非常感谢您的帮助。
【问题讨论】: