Question
How can I implement the $match stage with multiple conditions in MongoDB aggregation using the Java Driver?
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import java.util.Arrays;
// Create MongoDB client and connect to the database
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("exampleDB");
MongoCollection<Document> collection = database.getCollection("exampleCollection");
// Define the aggregation pipeline with multiple $match conditions
collection.aggregate(Arrays.asList(
Aggregates.match(Filters.and(
Filters.eq("status", "active"),
Filters.gt("age", 25)
))
)).forEach(doc -> System.out.println(doc.toJson()));
Answer
Using the $match stage with multiple conditions in MongoDB aggregation allows you to filter documents based on specific criteria before processing them further. The Java Driver for MongoDB provides simple methods to construct these queries, especially using the Filters class.
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import java.util.Arrays;
// Create MongoDB client and connect to the database
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("exampleDB");
MongoCollection<Document> collection = database.getCollection("exampleCollection");
// Define the aggregation pipeline with multiple $match conditions
collection.aggregate(Arrays.asList(
Aggregates.match(Filters.and(
Filters.eq("status", "active"),
Filters.gt("age", 25)
))
)).forEach(doc -> System.out.println(doc.toJson()));
Solutions
- Use the `Filters.and()` method to combine multiple conditions for the $match stage.
- Use the `Filters` class to specify conditions like equality, greater than, or less than as needed.
- Ensure your MongoDB Java Driver is up to date to avoid compatibility issues.
Common Mistakes
Mistake: Using the wrong syntax for Filters
Solution: Ensure you are importing the correct classes from the MongoDB library and that you are using 'Filters' to construct your BSON queries.
Mistake: Not accounting for data types in conditions
Solution: Make sure that the types in the conditions match the data types in the MongoDB documents, such as using integers for age.
Helpers
- MongoDB aggregation
- Java Driver aggregation
- $match multiple conditions
- MongoDB filters
- Java MongoDB
- Aggregation pipeline Java