How Java performs MongoDB aggregation operations, such as counting, summing, averaging, etc
To perform MongoDB aggregation operations in Java, you need to use MongoDB's Java driver. This driver is called "mongodb driver" and can be managed through Maven or Gradle for dependencies.
The following is a complete example code for MongoDB aggregation operations using Java:
1. Maven Dependency
<dependencies>
...
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
...
</dependencies>
Please update the driver version based on the MongoDB version you are using.
2. Java code examples
import com.mongodb.ConnectionString;
import com.mongodb.client.*;
import org.bson.Document;
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.*;
public class MongoDBAggregationExample {
public static void main(String[] args) {
//MongoDB Connection String
String connectionString = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false";
//Create MongoDB client
MongoClient mongoClient = MongoClients.create(new ConnectionString(connectionString));
//Get Database Objects
MongoDatabase database = mongoClient.getDatabase("test");
//Get Collection Object
MongoCollection<Document> collection = database.getCollection("students");
//Count using aggregation operations
long count = collection.countDocuments();
System.out.println("Total documents count: " + count);
//Using aggregation operations for summation
AggregateIterable<Document> sumResult = collection.aggregate(
List.of(group(null, sum("totalScore", "$score")))
);
Document sumDocument = sumResult.first();
int totalScore = sumDocument.getInteger("totalScore");
System.out.println("Total score sum: " + totalScore);
//Using aggregation operations for average calculation
AggregateIterable<Document> avgResult = collection.aggregate(
List.of(group(null, avg("averageScore", "$score")))
);
Document avgDocument = avgResult.first();
double averageScore = avgDocument.getDouble("averageScore");
System.out.println("Average score: " + averageScore);
//Close MongoDB connection
mongoClient.close();
}
}
In this example, we assume that there is a collection called "students" in the "test" database of MongoDB.
This example performs aggregation operations to count the number of documents, sum them, and calculate the average.
Sample document for MongoDB collection 'students':
json
{ "_id" : ObjectId("610f17d78096d61001a0caaf"), "name" : "Alice", "score" : 80 }
{ "_id" : ObjectId("610f17d78096d61001a0cab0"), "name" : "Bob", "score" : 75 }
{ "_id" : ObjectId("610f17d78096d61001a0cab1"), "name" : "Charlie", "score" : 90 }
{ "_id" : ObjectId("610f17d78096d61001a0cab2"), "name" : "David", "score" : 85 }
This example outputs the following content on the console:
Total documents count: 4
Total score sum: 330
Average score: 82.5
The above example is developed based on MongoDB Java driver v4.4.1, and can be modified accordingly according to the version you are currently using.