Mongodb选择所有字段按一个字段分组并按另一个字段排序 [英] Mongodb select all fields group by one field and sort by another field

查看:2052
本文介绍了Mongodb选择所有字段按一个字段分组并按另一个字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们收集带有以下字段的'消息'

We have collection 'message' with following fields

_id |   messageId |  chainId | createOn

1   |       1     |    A     | 155
2   |       2     |    A     | 185
3   |       3     |    A     | 225
4   |       4     |    B     | 226
5   |       5     |    C     | 228
6   |       6     |    B     | 300

我们希望按以下标准选择所有文档字段

We want to select all fields of document with following criteria


  1. 受字段'chainId'的干扰


  2. 按desc中的'createdOn'排序(排序)

因此,预期结果是

_id |   messageId |  chainId | createOn

3   |       3     |    A     | 225
5   |       5     |    C     | 228
6   |       6     |    B     | 300

我们在java应用程序中使用spring-data。我尝试使用不同的方法,到目前为止没有任何帮助。

是否可以通过单个查询实现上述目标?

We are using spring-data in our java application. I tried to go with different approaches, nothing helped me so far.
Is it possible to achieve above with single query?

推荐答案

您想要的是使用聚合框架可以实现的目标。 (对其他人有用)的基本形式是:

What you want is something that can be achieved with the aggregation framework. The basic form of ( which is useful to others ) is:

db.collection.aggregate([

    // Group by the grouping key, but keep the valid values
    { "$group": {
        "_id": "$chainId",
        "docId": { "$first": "$_id" },
        "messageId": { "$first": "$messageId" },
        "createOn": { "$first": "$createdOn" }
    }},

    // Then sort
    { "$sort": { "createOn": -1 } }

])

因此,在a的messageId的不同值上分组 href =http://docs.mongodb.org/manual/reference/operator/aggregation/first/#grp._S_first =noreferrer> $ first 每个其他字段的边界值。或者,如果您想要最大的,请使用 $ last ,但对于最小或最大的行,它可能是有意义的 $ sort 只需使用 $ min $ max

So that "groups" on the distinct values of "messageId" while taking the $first boundary values for each of the other fields. Alternately if you want the largest then use $last instead, but for either smallest or largest by row it probably makes sense to $sort first, otherwise just use $min and $max if the whole row is not important.

请参阅MongoDB aggregate() 文档,了解有关使用的更多信息,如w ell作为驱动程序JavaDocs和SpringData Mongo连接器文档,以便更多地使用聚合方法和可能的帮助程序。

See the MongoDB aggregate() documentation for more information on usage, as well as the driver JavaDocs and SpringData Mongo connector documentation for more usage of the aggregate method and possible helpers.

这篇关于Mongodb选择所有字段按一个字段分组并按另一个字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆