Implementing MongoDB aggregation queries using Java

The use of Java to implement various aggregation queries in MongoDB is mainly achieved through MongoDB's Java driver. Before using Java to implement aggregate queries, it is necessary to ensure that the MongoDB environment and Java development environment have been correctly configured. The following is an example code that demonstrates how to use Java to implement various aggregation queries in MongoDB: Firstly, Maven needs to be used to add Java driver dependencies for MongoDB. Add the following dependencies to the pom.xml file of the project: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.1.1</version> </dependency> Next, the following example code can be used to implement various aggregation queries: import com.mongodb.MongoClientSettings; import com.mongodb.client.AggregateIterable; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AggregationQueryExample { public static void main(String[] args) { //Connect to MongoDB database MongoClientSettings settings = MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017)))) .build(); MongoClient mongoClient = MongoClients.create(settings); //Select Database and Collection MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> collection = database.getCollection("mycollection"); //Aggregation Query Example AggregateIterable<Document> result = collection.aggregate(Arrays.asList( new Document("$group", new Document("_id", "$category").append("total", new Document("$sum", "$amount"))), new Document("$match", new Document("total", new Document("$gte", 1000))) )); //Output Results for (Document document : result) { System.out.println(document); } //Close Connection mongoClient.close(); } } In the above example, a MongoClient object was first created to connect to the MongoDB database. Then select the database to operate on through the getDatabase method, and then select the collection to operate on through the getCollection method. Aggregation queries are implemented through the aggregate method, passing in a list containing aggregation pipeline operations that can be aggregated using multiple operations. In the example, the $group operation and $match operation were used to implement aggregate queries, and the query results were printed out through a loop. Finally, use the close method to close the connection to MongoDB. It should be noted that the database name and collection name in the example need to be modified according to the actual situation. The above is the method and sample code for implementing various aggregation queries in MongoDB using Java.