Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava

Retrieve Data

On this page

  • Overview
  • Find Operation
  • Aggregate Operation
  • Change Streams

In this guide, you can learn how to retrieve data from your MongoDB database. To retrieve data, use read operations.

Read operations allow you to do the following:

  • Retrieve a subset of documents from your collection using a find operation

  • Perform transformations on retrieved documents from your collection using an aggregate operation

  • Monitor real-time changes to your database using a change stream

The following sections feature examples of how the owner of a paint store manages their customers' orders. For each order, the owner keeps track of the color and quantity, which corresponds to the color and qty fields in their paint_order collection:

{ "_id": 1, "color": "purple", "qty": 10 }
{ "_id": 2, "color": "green", "qty": 8 }
{ "_id": 3, "color": "purple", "qty": 4 }
{ "_id": 4, "color": "green", "qty": 11 }

Use the find operation to retrieve a subset of your existing data in MongoDB. You can specify what data to return including which documents to retrieve, in what order to retrieve them, and how many to retrieve.

To perform a find operation, call the find() method on an instance of a MongoCollection. This method searches a collection for documents that match the query filter you provide. For more information on how to specify a query, see our Specify a Query guide.

The owner would like to know which orders contain greater than three, but less than nine cans of paint from their paint_order collection.

To address this scenario, the owner finds orders to match the criteria:

Bson filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9));
collection.find(filter).forEach(doc -> System.out.println(doc.toJson()));

For more information on how to build filters, see our Filters Builders guide.

The following shows the output of the preceding query:

{ "_id": 2, "color": "green", "qty": 8 }
{ "_id": 3, "color": "purple", "qty": 4 }

After the owner runs this query, they find two orders that matched the criteria.

For a runnable find() example, see our Find Multiple Documents page.

Use the aggregate operation to perform the stages in an aggregation pipeline. An aggregation pipeline is a multi-staged transformation that produces an aggregated result.

To perform an aggregate operation, call the aggregate() method on an instance of a MongoCollection. This method accepts aggregation expressions to run in sequence. To perform aggregations, you can define aggregation stages that specify how to match documents, rename fields, and group values. For more information, see our Aggregation guide.

The owner would like to know which paint color is the most purchased (highest quantity sold) from their paint_order collection.

To address the scenario, the owner creates an aggregation pipeline that:

  • Matches all the documents in the paint_order collection

  • Groups orders by colors

  • Sums up the quantity field by color

  • Orders the results by highest-to-lowest quantity

Bson filter = Filters.empty();
collection.aggregate(Arrays.asList(
Aggregates.match(filter),
Aggregates.group("$color", Accumulators.sum("qty", "$qty")),
Aggregates.sort(Sorts.descending("qty"))))
.forEach(doc -> System.out.println(doc.toJson()));

The following shows the output of the preceding aggregation:

{ "_id": "green", "qty": 19 }
{ "_id": "purple", "qty": 14 }

After the owner runs the aggregation, they find that "green" is the most purchased color.

For more information on how to construct an aggregation pipeline, see the MongoDB Server manual page on Aggregation.

Open a change stream to monitor real-time changes to a collection. Change streams can subscribe to specific types of data changes and immediately produce change events. For more information on change streams, see the MongoDB server manual page on Change Streams.

To open a change stream, call the watch() method on an instance of a MongoCollection, MongoDatabase, or MongoClient. You can pass an aggregation pipeline to this method to notify you as soon as a change occurs.

Important

Change streams don't support standalone MongoDB instances because standalone MongoDB instances don't have an oplog.

The instance you call the watch() method on determines the scope of events which the change stream listens for. If you call watch() on a MongoCollection, the method monitors a collection. If you call watch() on a MongoDatabase, the method monitors all the collections in the database. If you call watch() on a MongoClient, the method monitors a standalone MongoDB instance, a replica set, or a sharded cluster.

The owner would like to receive notifications for when customers submit new orders or update their orders in the paint_order collection.

To address this scenario, the owner:

  • Creates an aggregation pipeline that filters for "insert" and "update" operation types

  • Creates a change stream on the aggregation pipeline

  • Prints changes picked up by the change stream

List<Bson> pipeline = Arrays.asList(
Aggregates.match(Filters.in("operationType", Arrays.asList("insert", "update"))));
ChangeStreamIterable<Document> changeStream = database.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
changeStream.forEach(event ->
System.out.println("Received a change to the collection: " + event));

After creating the change stream, the owner gets notifications for future inserts or updates to their collection.

An insert notification looks similar to the following:

Received a change to the collection: ChangeStreamDocument{
operationType=OperationType{value='insert'},
resumeToken={"_data": "825EC..."},
namespace=database.collection,
...
}

For a runnable watch() example, see our Watch For Changes page.

For additional information on the methods mentioned on this page, see the following API Documentation:

←  Read OperationsAccess Data From a Cursor →