【问题标题】:Spring Data Mongodb Query Group BySpring Data Mongodb 查询分组方式
【发布时间】: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


【解决方案1】:

更新

我设法让它工作:

TypedAggregation<Notifications> aggregation = newAggregation(Notifications.class,
                 match(Criteria.where("idUser").is(idUser)),
                 group("title").push("$$ROOT").as("notifications")
            );
        AggregationResults<Notifications> results = mongoOperations.aggregate(aggregation, Notifications.class);

        return results.getRawResults();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2018-11-25
    • 2014-11-28
    相关资源
    最近更新 更多