簡體   English   中英

如何使用 java 驅動程序在 MongoDb 中搜索和計算路徑值

[英]How to search and count paths values in MongoDb using java driver

我想查看具有相同基本路徑的集合中有多少文檔:我的 mongoDb 結構如下:

        {
            {_id:1,
             tag1: a, 
             path: C:\Users\A\Downloads\1\qwerty
            }, 
            {
            _id: 2,
            tag1: b,
            path: C:\Users\A\Downloads\2\abcd
            },
            {
             _id: 3, 
            tag1: alfa,
            path: C:\Users\A\Documents\3\fsdf
            },
            {
            _id: 4,
            tag1: beta,
            path: C:\Users\A\Documents\4\aaa
            }
        }

例如,我想搜索 C:\\Users\\A\\Downloads 中有多少個元素以及 C:\\Users\\A\\Documents 中有多少個元素。 我該怎么做?

我想查看具有相同基本路徑的集合中有多少文檔:

假設您提供基本路徑以查找具有該基本路徑的文檔數量 - 以下正則表達式查詢將計算path字段值以“C:\\Users\\A\\Downloads\\” 開頭的所有文檔。

db.paths.find( { path: /^C:\\Users\\A\\Downloads\\/ } ).count()


使用 MongoDB Java 驅動程序的代碼:

Pattern p = Pattern.compile("^C:\\\\Users\\\\A\\\\Documents\\\\");
Bson queryFilter = regex("path", p);
long count = collection.countDocuments(filter);



以下是我使用的數據; 有4個文件。 當我運行代碼時,我得到的計數為 2 (這是正確和預期的,因為有兩條路徑與模式“^C:\\\\Users\\\\A\\\\Documents\\\\”匹配)。

在此處輸入圖片說明



使用與 Compass 屏幕截圖中顯示的數據相同的數據,以下聚合

db.paths.aggregate( [ { $group : { _id : "Counts", Documents: { $sum: { $cond: [ { $regexMatch: { input: "$path" , regex: /^C:\\\\Users\\\\A\\\\Documents\\\\/ } }, 1, 0 ] } }, Downloads: { $sum: { $cond: [ { $regexMatch: { input: "$path" , regex: /^C:\\\\Users\\\\A\\\\Downloads\\\\/ } }, 1, 0 ] } } } }, ] )

印刷:

 { "_id" : "Counts", "Documents" : 2, "Downloads" : 1 }


上述聚合的Java代碼

 Pattern docPattern = Pattern.compile("^C:\\\\\\\\Users\\\\\\\\A\\\\\\\\Documents\\\\\\\\"); Pattern downloadPattern = Pattern.compile("^C:\\\\\\\\Users\\\\\\\\A\\\\\\\\Downloads\\\\\\\\"); List<Bson> pipeline = Arrays.asList(new Document("$group", new Document("_id", "Counts") .append("document_counts", new Document("$sum", new Document("$cond", Arrays.asList( new Document("$regexMatch", new Document("input", "$path") .append("regex", docPattern)), 1L, 0L ) ) ) ) .append("download_counts", new Document("$sum", new Document("$cond", Arrays.asList( new Document("$regexMatch", new Document("input", "$path") .append("regex", downloadPattern)), 1L, 0L ) ) ) ) ), project(excludeId()) ); List<Document> results = new ArrayList<>(); collection.aggregate(pipeline).into(results); results.forEach(System.out::println);

結果文件:

 Document{ { document_counts=2, download_counts=1 } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM