How to Use the $match Stage with Multiple Conditions in MongoDB Aggregation using Java Driver

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

Related Questions

⦿How to Use Handler Method Parameters in Eclipse RCP 4

Learn how to effectively use handler method parameters in Eclipse RCP 4 applications. Structured guide with examples and common mistakes.

⦿How to Solve the Dutch National Flag Problem for Large Arrays

Explore solutions to the Dutch National Flag problem including detailed explanations and common pitfalls in handling large arrays.

⦿How to Resolve Cache Invalidation Issues in Apache Shiro?

Learn how to fix cache invalidation problems in Apache Shiro with practical solutions and common debugging tips.

⦿When Should You Avoid Making a Singleton Thread-Safe?

Explore scenarios where making a Singleton class threadsafe may not be necessary along with pitfalls and best practices.

⦿Is Object State Set in the Constructor Visible Across All Threads?

Explore whether the state of an object initialized in its constructor is visible to all threads in a multithreaded environment.

⦿How to Set a Property from a Static List String Property Using OGNL in Struts2?

Learn how to correctly set a property from a static list string property using OGNL in Struts2 with expert tips and code examples.

⦿Understanding RMI Theory: Stubs and Distributed Garbage Collection Explained

Dive into RMI theory with a detailed explanation of stubs and distributed garbage collection in Java. Learn the fundamentals and best practices.

⦿How to Efficiently Allocate Large Numbers of Small Objects in Java

Learn efficient strategies for allocating numerous small objects in Java to optimize memory use and performance.

⦿How to Effectively Render a Heat Map Using Programming Techniques?

Learn stepbystep how to render a heat map using advanced programming techniques for data visualization.

⦿How Does the Virtual Machine Select the Appropriate Method for Execution?

Discover how virtual machines determine the correct method for execution including insights into method resolution and factors influencing the selection process.

© Copyright 2025 - CodingTechRoom.com