【问题标题】:Aggregation with projection投影聚合
【发布时间】:2018-12-08 21:09:15
【问题描述】:

虽然我不明白如何实现我的目标,但我一直在搜索许多聚合方法。以下代码中AggregateIterable 中包含的文档仅包含Aggregates.group(...) 中提到的_idcopies 2 个字段。我如何同时包含 field1field2 字段?

AggregateIterable<Document> items = itemCollection.aggregate(Arrays.asList(
    Aggregates.project(include("_id","field1","field2")),
    Aggregates.group("$_id",Accumulators.sum("copies",1)),
    Aggregates.sort(descending("field1")))
);

我不知所措,因为我似乎找不到(或至少理解)任何示例。任何帮助将不胜感激,尤其是我希望如何做的示例。

【问题讨论】:

    标签: java mongodb aggregation-framework


    【解决方案1】:

    mongo 中的 $group agg 函数要求您明确包含任何输出列,同时使用组友好的转换。如果你想要少数几个领域的 ghetto passthru,我相信有一个 $first 运算符可以发挥作用。

    它与包含对象的 c# linq group() 函数不同。如果您需要该功能(键的值集合中的各种不匹配对象),则必须提前实例化结果,然后使用标准 linq 组函数。

    【讨论】:

    • 你能举个例子或参考看看吗?
    【解决方案2】:

    这是我使用 first() 运算符的示例。

    AggregateIterable<Document> items = Main.itemCollection.aggregate(Arrays.asList(
        Aggregates.project(fields(include("field1","field2"),excludeId())),
        Aggregates.group(
            "$field1",
            first("field2","$field2r")
            Accumulators.sum("Copies",1)
        ),
        Aggregates.sort(descending("_id"))
    ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      • 2015-09-30
      • 2014-05-04
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      相关资源
      最近更新 更多