简体   繁体   English

投影汇总

[英]Aggregation with projection

Been searching through many methods of aggregation although I cant understand how to achieve my goal. 尽管无法理解如何实现目标,但仍在通过多种聚合方法进行搜索。 The documents contained within the AggregateIterable in the following code only contain the 2 fields _id and copies as mentioned in Aggregates.group(...) . 以下代码中AggregateIterable中包含的文档仅包含2个字段_idcopiesAggregates.group(...) How would I include the fields field1 and field2 aswell? 我还将如何包括字段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")))
);

I'm at a loss since I can't seem to find (or at least understand) any example. 我很茫然,因为我似乎找不到(或至少理解)任何例子。 Any help would be greatly appreciate, especially an example of how to do as I wish. 任何帮助将不胜感激,尤其是我希望如何做的一个例子。

the $group agg function in mongo requires you explicitly include any output columns, using a group-friendly transform as well. mongo中的$ group agg函数要求您还使用对组友好的转换来显式包括所有输出列。 If you want ghetto passthru for a few fields, i believe there is a $first operator that can come into play. 如果您想让贫民窟在某些领域通行,我相信这里可以有一个$ first算子。

It is NOT the same as the c# linq group() function where the obects are included regardless. 它与包含对象的c#linq group()函数不同。 If you need that functionality (various unmatched objects in the value collection for the key), you will have to instantiate the results earlier, then use the standard linq group function. 如果需要该功能(键的值集合中有许多不匹配的对象),则必须更早实例化结果,然后使用标准的linq group函数。

Here is the example of what I got working, using the first() operator. 这是我使用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"))
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM