无法使用 Java 代码在 MongoDB 聚合中获取最大 _id 值

声明:我正在尝试获取数据集的最大 _id 值。


问题:它返回所有 _id 值。


MongoCollection<Document> coll = db.getCollection(collection);          

AggregateIterable<Document> docs = coll.aggregate(Arrays.asList(Aggregates.match(Filters.eq("Dept", "IT")),Aggregates.group("$_id", Accumulators.max("_id", "$_id"))));

for(Document doc : docs) {System.out.println(doc.toJson());}


白猪掌柜的
浏览 155回答 3
3回答

泛舟湖上清波郎朗

问题:您正在分组并试图找到组中的_id最大值,这显然是每个组一个。_id相反,您需要从所有过滤的文档中找到最大值。下面的代码可以得到我们预期的输出:MongoCollection coll = db.getCollection(collection);AggregateIterable docs = coll.aggregate(Arrays.asList(Aggregates.match(Filters.eq("Dept", "IT")),&nbsp; &nbsp; &nbsp; &nbsp; Aggregates.group(null, Accumulators.max("_id", "$_id"))));for (Document doc : docs) {&nbsp; &nbsp; System.out.println(doc.toJson());}

哔哔one

解决方案:我们需要对非聚合字段进行分组。代码:MongoCollection<Document> coll = db.getCollection(collection);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;AggregateIterable<Document> docs = coll.aggregate(&nbsp; &nbsp; &nbsp; &nbsp; Arrays.asList(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Aggregates.match(Filters.eq("Dept", "IT")),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Aggregates.group("EmpId", Accumulators.max("id", "$_id"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; );for(Document doc : docs) {&nbsp; &nbsp; System.out.println(doc.toJson());}

30秒到达战场

例如:您可以试试这个通过使用这个我从列中获取最大日期logDate并将其分组为 MachineNames(根据我的要求)MongoCollection<Document>&nbsp;collection&nbsp;&nbsp;=&nbsp;databases.getCollection("Smx_22234_ShiftOEEDaily"); AggregateIterable<Document>&nbsp;maxLogDate&nbsp;=&nbsp;collection.aggregate(Arrays.asList(Aggregates.group("$machineName",&nbsp;Accumulators.max("maxlogdate",&nbsp;"$logDate"))));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java