亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用 Java 代碼在 MongoDB 聚合中獲取最大 _id 值

無法使用 Java 代碼在 MongoDB 聚合中獲取最大 _id 值

白豬掌柜的 2023-06-08 20:50:06
聲明:我正在嘗試獲取數據集的最大 _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());}
查看完整描述

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());

}


查看完整回答
反對 回復 2023-06-08
?
嗶嗶one

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());

}


查看完整回答
反對 回復 2023-06-08
?
30秒到達戰場

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"))));



查看完整回答
反對 回復 2023-06-08
  • 3 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號