Search code examples
mongodbaggregation-frameworkmongodb-java

Java Syntax for a Mongo Aggregation Query


I have got stuck with the Java syntax for a Mongo query.

I have written the Mongo query for console but I want the corresponding Java syntax for that query.

Here's the shell command:

db.errorsegmentaudit.aggregate([
    {$sort:{timestamp:1}},
    {$limit:1},
    {$unwind:"$auditErrorTypeCounts"},
    {$unwind:"$auditErrorTypeCounts.auditErrorCounts"}, 
    {$group: {
            _id: {
                "agent": "$auditErrorTypeCounts.auditErrorCounts.agentName", 
                "type":"$auditErrorTypeCounts.typeOfError"
            }, 
            count: {
                $sum: "$auditErrorTypeCounts.auditErrorCounts.countOfErrors"
            }
        }    
    } 
])

I have gone through the documentation and all but didn't find the right one. I tried using Aggregation class in Java but it didn't work.


Solution

  • The MongoDB Java driver (using version 3.x) equivalent of the MongoDB shell command in your question is:

    MongoClient mongoClient = ...;
    
    MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("..");
    
    AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
            // $sort:{timestamp:1}
            Aggregates.sort(Sorts.ascending("timestamp")),
    
            // $limit:1
            Aggregates.limit(1),
    
            // $unwind:"$auditErrorTypeCounts"
            Aggregates.unwind("$auditErrorTypeCounts"),
    
            // $unwind:"$auditErrorTypeCounts.auditErrorCounts"
            Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts"),
    
            // $group:{...}
            Aggregates.group(
                    // _id:{"agent":"$auditErrorTypeCounts.auditErrorCounts.agentName","type":"$auditErrorTypeCounts.typeOfError"}
                    new Document("agent", "$auditErrorTypeCounts.auditErrorCounts.agentName").append("type", "$auditErrorTypeCounts.typeOfError"),
    
                    // count:{$sum:"$auditErrorTypeCounts.auditErrorCounts.countOfErrors"}}}
                    Accumulators.sum("count", "$auditErrorTypeCounts.auditErrorCounts.countOfErrors")
            )
    ));
    

    The comments above each stage in the aggregation pipeline show which shell command the Java code mirrors. For example:

    // $unwind:"$auditErrorTypeCounts.auditErrorCounts"
    Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts")
    

    ... shows you that the Java equivalent to the shell command $unwind:"$auditErrorTypeCounts.auditErrorCounts" is Aggregates.unwind("$auditErrorTypeCounts.auditErrorCounts"). This may make it easier for you to map one to the other.

    More details in the MongoDB Java driver docs.