【问题标题】:Java mongodb aggregation count occurrencesJava mongodb 聚合计数出现
【发布时间】:2021-05-31 15:23:23
【问题描述】:

我有一些这样的文件:

{
  "user": '1'
},
{ "user": '1'
},
{
  "user": '2'
},
{
  "user": '3'
}

我希望能够获得一组所有不同用户及其各自的计数,按降序排序。所以我的输出会是这样的:

{
  '1': 2,
  '2': 1,
  '3': 1
}

所以,在 mongodb 中是:

db.collection.aggregate(
   {$group : { _id : '$user', count : {$sum : 1}}}
).result

但我想在 java 中做到这一点。我试过这个:

AggregateIterable it = collection.aggregate(Arrays.asList(
        group("$id", Accumulators.sum("$user", 1)),
        sort(Sorts.descending("$user"))
));

但这是错误的......我该怎么做?

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    试试这个:

    AggregateIterable it = collection.aggregate(Arrays.asList(
        group("$user", Accumulators.sum("count", 1)),
        sort(Sorts.descending("count"))
    ));
    

    【讨论】:

    • 谢谢!,如果我想显示文档的另一个字段怎么办?
    • 您可以像这样计算另一个字段作为组的一部分:group("$customerId", sum("totalQuantity", "$quantity"), avg("averageQuantity", "$quantity")),但是,如果您希望原始文档中的字段出现,请尝试使用 facet。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多