【发布时间】:2020-10-07 23:25:46
【问题描述】:
我将 Spring 与 mongodb 一起使用,我想构建一个查询以使用 GROUP BY (如 SQL)按标题对我的文档进行分组,我有 3 个文档:
{
_id: 5eeabfda75204e17242d3ff4,
title: "Review",
message: "hi this is a review 1",
created: 2020-06-18T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
},
{
_id: 5eeabfda75204e17242d3ff5,
title: "Review",
message: "hi this is a review 2",
created: 2020-06-15T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
},
{
_id: 5eeabfda75204e17242d3ff6,
title: "Reservation",
message: "hi this is a a reservation",
created: 2020-06-15T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
}
预期结果:我想让我的文档按标题分组:
{
"Review": [
{
_id: 5eeabfda75204e17242d3ff4,
title: "Review",
message: "hi this is a review 1",
created: 2020-06-18T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
},
{
_id: 5eeabfda75204e17242d3ff5,
title: "Review",
message: "hi this is a review 2",
created: 2020-06-15T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
},
],
"Reservation": [
{
_id: 5eeabfda75204e17242d3ff6,
title: "Reservation",
message: "hi this is a a reservation",
created: 2020-06-15T00: 18: 35.608+00: 00,
_class: "com.guestnhousebackpfe.models.Notifications"
}
]
}
我怎样才能做到这一点?
【问题讨论】:
-
您可以发布您尝试过的查询吗?
-
您使用带有$group 阶段的聚合查询来获取结果。您需要按
title字段分组并使用$push聚合运算符将文档存储到数组中。 -
它有效,但将 id 作为对象返回:“_id”:{“timestamp”:1592442842,“counter”:2965492,“date”:“2020-06-18T01:14:02.000+0000” , "时间": 1592442842000, "timeSecond": 1592442842, "processIdentifier": 5924, "machineIdentifier": 7675982 },
标签: mongodb spring-boot group-by mongodb-query aggregation-framework