[英]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);
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.