Docs Menu

Builders

On this page

  • Overview
  • Why Use Builders?
  • Scenario
  • Using the MongoDB Shell
  • Without Using Builders
  • Using Builders
  • Available Builders

This section includes guides on how to use each of the available builders, and demonstrates the utility the MongoDB Java driver builder classes provide.

The Java driver provides classes to simplify the process for developers to use CRUD operations and the Aggregation API. The static utility methods allow you to build a query more efficiently.

Using the builders class, you leverage the power of:

  • The Java compiler and the IDE to find errors during development
  • The IDE for discovery and code completion

When using builders, the Java compiler and the IDE catch errors such as misspelled operators early on. When using the MongoDB shell or plain Java, you write operators as strings and get no visual indication of a problem, pushing these errors to runtime instead of compile time

With the builder classes, you write operators as methods. The IDE instantly underlines and gives you a red bar on the right indicating something is wrong. While developing, the IDE also shows you the methods you can use. It automatically completes your code with placeholder parameters once you select which method you want to use.

Imagine we want to send a marketing email to all users in our users collection with the following criteria:

  • Users that identify as "female" gender
  • Users that are older than "29"

We only want their email address, so we'll ensure our query doesn't return data we pay bandwidth costs for but don't need.

collection.find({ "gender": "female", "age" : { "$gt": 29 }}, { "_id": 0, "email": 1 })
Bson filter = new Document().append("gender", "female").append("age", new Document().append("$gt", 29));
Bson projection = new Document().append("_id", 0).append("email", 1);
collection.find(filter).projection(projection);
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
...
Bson filter = and(eq("gender", "female"), gt("age", 29));
Bson projection = fields(excludeId(), include("email"));
collection.find(filter).projection(projection);
Give Feedback
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.