Docs Menu
Docs Home
/ / /
Node.js
/ / /

Retrieve Data

On this page

  • Overview
  • Find Documents
  • Aggregate Data from Documents
  • Monitor Data Changes

You can perform find operations to retrieve data from your MongoDB database. You can perform a find operation to match documents on a set of criteria by calling the find() or findOne() method.

Tip

Interactive Lab

This page includes a short interactive lab that demonstrates how to retrieve data by using the find() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.

To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button () in the top-right corner of the lab pane.

You can also further specify the information that the find operation returns by specifying optional parameters or by chaining other methods, as shown in the following guides:

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.

You can use the Node.js driver to connect and perform read operations for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB

  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB

To learn more about performing read operations in the Atlas UI for deployments hosted in MongoDB Atlas, see View, Filter, and Sort Documents.

You can call the find() method on a Collection object. 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 the Specify a Query guide.

Tip

No Query Criteria

To execute a find operation that has no query criteria, you can pass an empty query or omit the query document in your find method parameters.

The following operations both return all documents in the myColl collection:

await myColl.find(); // no query
await myColl.find({}); // empty query

If you don't pass a query or pass an empty query to the findOne() method, the operation returns a single document from a collection.

You can specify options in a find operation even when you pass an empty query. For example, the following code shows how you can specify a projection as an option while executing a find operation with an empty query parameter:

const options = {
projection: { _id: 0, field1: 1 },
};
const findResult = await myColl.findOne({}, options);

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 findResult.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 aggregateResult.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 commands 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 Operations