Docs Home → Develop Applications → MongoDB Drivers → Node.js
On this page
- Overview
- Find
- Aggregate
- Watch / Subscribe
This version of the documentation is archived and no longer supported. View the
current documentation to learn how to upgrade your version of the MongoDB Node.js driver.
Overview
You can use read operations to retrieve data from your MongoDB database.There are multiple types of read operations that access the data indifferent ways. If you want to request results based on a set of criteriafrom the existing set of data, you can use a find operation such as thefind()
or findOne()
methods.
You can also further specify the information you are requesting byincluding additional parameters or by chaining other methods such as:
You can also use an aggregation operation to retrieve data. This type ofoperation allows you to apply an ordered pipeline of transformations to thematched data.
If you want to monitor the database for incoming data that matches a set ofcriteria, you can use the watch operation to be notified in real-time whenmatching data is inserted.
Note
Your query operation may return a reference to acursor that contains matching documents. To learn how toexamine data stored in the cursor, see theCursor Fundamentals page.
Find
You can call the find()
method on a Collection
object. Themethod accepts a query document that describes the documents you want toretrieve. 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 canpass an empty query or omit the query document in your findmethod parameters.
The following operations both return all documents in themyColl
collection:
await myColl.find(); // no query await myColl.find({}); // empty query
If you don't pass a query or pass an empty queryto the findOne()
method, the operation returns a singledocument from a collection.
You can specify options in a find operation even when you pass anempty query. For example, the following code shows how you canspecify a projection as an option while executing a find operationwith an empty query parameter:
const options = { projection: { _id: 0, field1: 1 }, }; const findResult = await myColl.findOne({}, options);
To access the results, you can optionally pass a callback in the methodcall or resolve the returned Promise
object. See our guide onPromises and Callbacks for moreinformation.
If you resolve the Promise
returned by find()
, you receivea reference to a Cursor
with which you can navigate matched documents.If you resolve the Promise
returned by findOne()
, you receive thematching document or null
if there are no matches.
Example
A pizza restaurant wants to find all pizzas ordered by Lemony Snicketyesterday. They run the following find()
query on theorders
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 aCursor
. 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: ...}, ... ]
Aggregate
If you want to run a custom processing pipeline to retrieve data from yourdatabase, you can use the aggregate()
method. This method acceptsaggregation 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 tosummarize pizza orders over the past week. They run the followingaggregate()
query on the orders
collection to fetch thetotals 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 aCursor
. 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 aggregationfor more information on how to construct an aggregation pipeline.
Watch / Subscribe
You can use the watch()
method to monitor a collection for changes toa collection that match certain criteria. These changes include inserted,updated, replaced, and deleted documents. You can pass this methoda pipeline of aggregation commands that sequentially runs on the changeddata whenever write operations are executed on the collection.
Example
A pizza restaurant wants to receive a notification whenever a new pizzaorder comes in. To accomplish this, they create an aggregation pipelineto filter on insert operations and return specific fields. They passthis 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, seethe change streams usage example.