3 回答

TA貢獻1818條經驗 獲得超3個贊
問題:您正在分組并試圖找到組中的_id最大值,這顯然是每個組一個。_id相反,您需要從所有過濾的文檔中找到最大值。
下面的代碼可以得到我們預期的輸出:
MongoCollection coll = db.getCollection(collection);
AggregateIterable docs = coll.aggregate(Arrays.asList(Aggregates.match(Filters.eq("Dept", "IT")),
Aggregates.group(null, Accumulators.max("_id", "$_id"))));
for (Document doc : docs) {
System.out.println(doc.toJson());
}

TA貢獻1854條經驗 獲得超8個贊
解決方案:我們需要對非聚合字段進行分組。
代碼:
MongoCollection<Document> coll = db.getCollection(collection);
AggregateIterable<Document> docs = coll.aggregate(
Arrays.asList(
Aggregates.match(Filters.eq("Dept", "IT")),
Aggregates.group("EmpId", Accumulators.max("id", "$_id"))
)
);
for(Document doc : docs) {
System.out.println(doc.toJson());
}

TA貢獻1828條經驗 獲得超6個贊
例如:您可以試試這個通過使用這個我從列中獲取最大日期logDate
并將其分組為 MachineNames(根據我的要求)
MongoCollection<Document> collection = databases.getCollection("Smx_22234_ShiftOEEDaily"); AggregateIterable<Document> maxLogDate = collection.aggregate(Arrays.asList(Aggregates.group("$machineName", Accumulators.max("maxlogdate", "$logDate"))));
添加回答
舉報