i want to see how many documents I have in a collection with the same base path: my mongoDb is structured like this:
{
{_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
}
}
I want to search, for example, how many elements there are in C:\\Users\\A\\Downloads and how many elements there are in C:\\Users\\A\\Documents. How can I do it?
i want to see how many documents I have in a collection with the same base path:
Assuming you are supplying the base path to find the number of documents with that base path - the following regex query will count all the documents with the path
field value staring with "C:\\Users\\A\\Downloads\\".
db.paths.find( { path: /^C:\\Users\\A\\Downloads\\/ } ).count()
Code Using MongoDB Java Driver:
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 ] } } } }, ] )
prints:
{ "_id" : "Counts", "Documents" : 2, "Downloads" : 1 }
The Java code for the above aggregation:
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);
The result document:
Document{ { document_counts=2, download_counts=1 } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.