按 MongoDB 中的两个条目分组,包括日期部分
Group by two entries, including date part, in MongoDB
假设我在一个集合中有这些数据:
+--------+------------+---------+
| custId | date | payment |
+--------+------------+---------+
| 1 | 2020-03-23 | 87 |
+--------+------------+---------+
| 2 | 2020-03-07 | 65 |
+--------+------------+---------+
| 3 | 2020-02-18 | 23 |
+--------+------------+---------+
| 1 | 2020-05-06 | 42 |
+--------+------------+---------+
| 3 | 2020-04-09 | 9 |
+--------+------------+---------+
因此,MongoDb 中的数据如下所示:
[
{
"custId": 1,
"date": "2020-03-23",
"payment": 87
},
{
"custId": 2,
"date": "2020-03-07",
"payment": 65
},
{
"custId": 3,
"date": "2020-02-18",
"payment": 23
},
{
"custId": 1,
"date": "2020-05-06",
"payment": 42
},
{
"custId": 3,
"date": "2020-04-09",
"payment": 9
}
]
现在,我想按月获取客户 和 的付款总和。在 SQL 中,我会 运行:
SELECT custId, STRFTIME(date, '%Y-%m') as month, SUM(payment) FROM table GROUP BY custId, month
(或类似的东西,取决于数据库)
如果我只想按客户分组,我认为它应该是这样的:
[
{
"$group": {
"_id": "$custId",
"sum": {
"$sum": "$payment"
}
}
}
]
我不明白如何按 两个 条目进行分组,以及如何从日期中提取月份。
您可以在 $group
的 _id
字段中指定多个键。请注意,有必要将使用 $toDate
的日期转换为 MongoDB 可以使用的实际日期数据类型。您可能要考虑将其直接存储为 Date。
db.test.aggregate([
{
$group: {
_id: {
"custId": "$custId",
"year-month": {
$dateToString: {
format: "%Y-%m",
date: {
$toDate: "$date"
}
}
}
},
sum: {
$sum: "$payment"
}
}
}
]);
假设我在一个集合中有这些数据:
+--------+------------+---------+
| custId | date | payment |
+--------+------------+---------+
| 1 | 2020-03-23 | 87 |
+--------+------------+---------+
| 2 | 2020-03-07 | 65 |
+--------+------------+---------+
| 3 | 2020-02-18 | 23 |
+--------+------------+---------+
| 1 | 2020-05-06 | 42 |
+--------+------------+---------+
| 3 | 2020-04-09 | 9 |
+--------+------------+---------+
因此,MongoDb 中的数据如下所示:
[
{
"custId": 1,
"date": "2020-03-23",
"payment": 87
},
{
"custId": 2,
"date": "2020-03-07",
"payment": 65
},
{
"custId": 3,
"date": "2020-02-18",
"payment": 23
},
{
"custId": 1,
"date": "2020-05-06",
"payment": 42
},
{
"custId": 3,
"date": "2020-04-09",
"payment": 9
}
]
现在,我想按月获取客户 和 的付款总和。在 SQL 中,我会 运行:
SELECT custId, STRFTIME(date, '%Y-%m') as month, SUM(payment) FROM table GROUP BY custId, month
(或类似的东西,取决于数据库)
如果我只想按客户分组,我认为它应该是这样的:
[
{
"$group": {
"_id": "$custId",
"sum": {
"$sum": "$payment"
}
}
}
]
我不明白如何按 两个 条目进行分组,以及如何从日期中提取月份。
您可以在 $group
的 _id
字段中指定多个键。请注意,有必要将使用 $toDate
的日期转换为 MongoDB 可以使用的实际日期数据类型。您可能要考虑将其直接存储为 Date。
db.test.aggregate([
{
$group: {
_id: {
"custId": "$custId",
"year-month": {
$dateToString: {
format: "%Y-%m",
date: {
$toDate: "$date"
}
}
}
},
sum: {
$sum: "$payment"
}
}
}
]);