共計 2103 個字符,預計需要花費 6 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
本篇文章給大家分享的是有關如何在 mongoDB 中利用 java 處理聚合函數,丸趣 TV 小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著丸趣 TV 小編一起來看看吧。
需要對 document 中的一個 tweet_list 集合中的一個屬性 timestamp_ms 進行排序。組內排序
使用聚合框架,通過 match,unwind,sort 等不同的組件創建一個管道。
類似 mysql 中的多層嵌套子查詢。
mongoDB 中 js 代碼
db.text.aggregate( // Initial document match (uses index, if a suitable one is available)
[
{ $match: { _id : ObjectId( 5ca95b4bfb60ec43b5dd0db5)
}},
// Expand the scores array into a stream of documents
{ $unwind: $tweet_list },
{ $match: {
tweet_list.timestamp_ms : 1451841845660
}},
// Sort in descending order
{ $sort: {
tweet_list.timestamp_ms : 1
}}
]
)
java 實現此聚合函數
java 中的 Aggregation 類,查詢條件的順序決定結果。
Aggregation agg = Aggregation.newAggregation( Aggregation.match(Criteria.where( _id).is(id)),
Aggregation.unwind(tweet_list),
Aggregation.sort(Sort.Direction.ASC, tweet_list.timestamp_ms),
Aggregation.project(tweet_list.timestamp_ms , tweet_list.text , tweet_list.created_at)
AggregationResults JSONObject results = mongoTemplate.aggregate(agg, text , JSONObject.class);
//System.out.println(results +results.getRawResults()); // 獲取到的結果是 document
//String res = results.getRawResults();
String json = com.mongodb.util.JSON.serialize(results.getRawResults());
System.out.println(JSON serialized Document: + json);
JSONObject jso= JSON.parseObject(json);
JSONArray resultss=jso.getJSONArray( results
System.out.println(resultss);
3. 擴展
管道 pipeline
以下的管道操作符可以按照任意順序組合在一起使用。每個操作符都會接受一連串文檔,對這些文檔做了類型轉換后,將轉換后的文檔作為結果傳遞給下一個操作符。直到最后一個管道操作符,將結果返回給客戶端。
篩選 match
盡可能將帥選放在管道的前部。兩個原因:
1. 先過濾掉不需要的文檔,減少管道的工作量。
2. 如果在 project 和 group 之前執行 match,查詢可以用索引。
3. 不能在 match 中使用地理空間操作符
投射 project
類似 select 操作??梢杂霉艿辣磉_式,數學表達式,日期表達式,字符表達式,邏輯表達式等。
分組 group
跟 mysql 中的分組比較像
排序 sort
1 升序 -1 降序
限制 limit
限制結果條數
跳過 skip
丟棄結果中的前 n 個文檔
拆分 unwind
把數組中的每個值拆分為單獨的文檔,例如此問題中需要對一個 document 中的 tweetlist 進行排序,可以使用 unwind 把 tweetlist 中的不同 map 拆分成不同的文檔。
結果返回
文檔
MapReduce
如果聚合框架中查詢語言不能不表達,需要用到 MapReduce。
使用:把問題拆分為多個小問題,把各個小問題發送到不同的機器上,每臺機器只負責完成一部分的工作,完成之后,再把零碎的解決方案合并。
步驟:
1. 映射 map:把操作映射到集合中每個文檔
2. 洗牌 shuffle:按照鍵值分組,并將產生的鍵值組成列表放到對應的鍵中。
3. 化簡 reduce:把列表中的值化簡成一個單值,值被返回,繼續 shuffle,然后最終每個鍵的列表只有一個值,即最終結果,
以上就是如何在 mongoDB 中利用 java 處理聚合函數,丸趣 TV 小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注丸趣 TV 行業資訊頻道。
向 AI 問一下細節