Docs Menu

Docs HomeNode.js

Retrieve Data

On this page

  • Overview
  • Find
  • Aggregate
  • Watch / Subscribe

You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.

You can also further specify the information you are requesting by including additional parameters or by chaining other methods such as:

You can also use an aggregation operation to retrieve data. This type of operation allows you to apply an ordered pipeline of transformations to the matched data.

If you want to monitor the database for incoming data that matches a set of criteria, you can use the watch operation to be notified in real-time when matching data is inserted.

Note

Your query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the Cursor Fundamentals page.

The find() method is called on the Collection object that references the collection you want to query. The method accepts a query document that describes the documents you want to retrieve. For more information on how to specify your query document, see our guide on how to Specify a Query.

If you resolve the Promise returned by find(), you receive a reference to a Cursor with which you can navigate matched documents. If you resolve the Promise returned by findOne(), you receive the matching document or null if there are no matches.

Example

A pizza restaurant wants to find all pizzas ordered by Lemony Snicket yesterday. They run the following find() query on the orders collection:

const findResult = await orders.find({
name: "Lemony Snicket",
date: {
$gte: new Date(new Date().setHours(00, 00, 00)),
$lt: new Date(new Date().setHours(23, 59, 59)),
},
});

Once the operation returns, the findResult variable references a Cursor. You can print the documents retrieved using the forEach() method as shown below:

await cursor.forEach(console.dir);

The output might resemble the following:

[
{ name: "Lemony Snicket", type: "horseradish pizza", qty: 1, status: "delivered", date: ... },
{ name: "Lemony Snicket", type: "coal-fired oven pizza", qty: 3, status: "canceled", date: ...},
...
]

See the find() and findOne() for fully-runnable examples.

If you want to run a custom processing pipeline to retrieve data from your database, you can use the aggregate() method. This method accepts aggregation expressions to run in sequence. These expressions let you filter, group, and arrange the result data from a collection.

Example

A pizza restaurant wants to run a status report on-demand to summarize pizza orders over the past week. They run the following aggregate() query on the orders collection to fetch the totals for each distinct "status" field:

const aggregateResult = await orders.aggregate([
{
$match: {
date: {
$gte: new Date(new Date().getTime() - 1000 * 3600 * 24 * 7),
$lt: new Date(),
},
},
},
{
$group: {
_id: "$status",
count: {
$sum: 1,
},
},
},
]);

Once the operation returns, the aggregateResult variable references a Cursor. You can print the documents retrieved using the forEach() method as shown below:

await cursor.forEach(console.dir);

The output might resemble the following:

[
{ _id: 'delivering', count: 5 },
{ _id: 'delivered', count: 37 },
{ _id: 'created', count: 9 }
]

See the MongoDB server manual pages on aggregation for more information on how to construct an aggregation pipeline.

You can use the watch() method to monitor a collection for changes to a collection that match certain criteria. These changes include inserted, updated, replaced, and deleted documents. You can pass this method a pipeline of aggregation comands that sequentially runs on the changed data whenever write operations are executed on the collection.

Example

A pizza restaurant wants to receive a notification whenever a new pizza order comes in. To accomplish this, they create an aggregation pipeline to filter on insert operations and return specific fields. They pass this pipeline to the watch() method called on the orders collection as shown below:

const changeStream = orders.watch([
{ $match: { operationType: "insert" } },
{
$project: {
"fullDocument.name": 1,
"fullDocument.address": 1,
},
},
]);
changeStream.on("change", change => {
const { name, address } = change.fullDocument;
console.log(`New order for ${name} at ${address}.`);
});

For a runnable example of the watch() method using the NodeJS driver, see the change streams usage example.

←  Read OperationsAccess Data From a Cursor →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.