|
| 1 | +======== |
| 2 | +Builders |
| 3 | +======== |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +.. toctree:: |
| 8 | + |
| 9 | + /fundamentals/builders/aggregates |
| 10 | + /fundamentals/builders/filters |
| 11 | + /fundamentals/builders/indexes |
| 12 | + /fundamentals/builders/projections |
| 13 | + /fundamentals/builders/sort |
| 14 | + /fundamentals/builders/updates |
| 15 | + |
| 16 | +.. contents:: On this page |
| 17 | + :local: |
| 18 | + :backlinks: none |
| 19 | + :depth: 2 |
| 20 | + :class: singlecol |
| 21 | + |
| 22 | +This section includes guides on how to use each of the available builders, and demonstrates the utility the Java driver |
| 23 | +builder classes provide. |
| 24 | + |
| 25 | +Overview |
| 26 | +-------- |
| 27 | + |
| 28 | +The Java driver provides classes to make it easier to use CRUD operations and the Aggregation API. The static utility methods |
| 29 | +allow you to build a query more succinctly. |
| 30 | + |
| 31 | + |
| 32 | +Imagine we want to send a marketing email to all users in our users collection that identify as "female" gender and are older than "29". |
| 33 | +We only need their email address, so we'll ensure our query doesn't return data we pay bandwidth |
| 34 | +costs for but don't need. |
| 35 | + |
| 36 | +Using JSON and the MongoDB shell, the query would look something like: |
| 37 | + |
| 38 | +.. code-block:: js |
| 39 | + |
| 40 | + collection.find({ "gender": "female", "age" : { "$gt": 29 }}, { "_id": 0, "email": 1 }) |
| 41 | + |
| 42 | +Without builders, we construct the query in Java as: |
| 43 | + |
| 44 | +.. code-block:: java |
| 45 | + |
| 46 | + Bson filter = new Document().append("gender", "female").append("age", new Document().append("$gt", 28)); |
| 47 | + Bson projection = new Document().append("_id", 0).append("email", 1); |
| 48 | + collection.find(filter).projection(projection); |
| 49 | + |
| 50 | +With builders, the query becomes: |
| 51 | + |
| 52 | +.. code-block:: java |
| 53 | + |
| 54 | + import static com.mongodb.client.model.Filters.*; |
| 55 | + import static com.mongodb.client.model.Projections.*; |
| 56 | + ... |
| 57 | + |
| 58 | + Bson filter = and(eq("gender", "female"), gt("age", 29)); |
| 59 | + Bson projection = fields(excludeId(), include("email")); |
| 60 | + collection.find(filter).projection(projection); |
| 61 | + |
| 62 | +Available Builders |
| 63 | +------------------ |
| 64 | + |
| 65 | +- :ref:`Filters <filters-builders>` for building query filters. |
| 66 | +- :ref:`Projections <projections-builders>` for building projections. |
| 67 | +- :ref:`Sorts <sorts-builders>` for building sort criteria. |
| 68 | +- :ref:`Updates <updates-builders>` for building updates. |
| 69 | +- :ref:`Aggregates <aggregates-builders>` for building aggregation pipelines. |
| 70 | +- :ref:`Indexes <indexes-builders>` for creating index keys. |
0 commit comments