Retrieve Data (2024)

Docs HomeDevelop ApplicationsMongoDB DriversNode.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: ...},
...
]

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

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 orderscollection 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.

Retrieve Data (2024)
Top Articles
11 Best CD Rates Of September 2024: Up To 5.25%
Our Top 5 Healthiest Red Wine Picks
Christian McCaffrey loses fumble to open Super Bowl LVIII
Craigslist Monterrey Ca
Dte Outage Map Woodhaven
Crocodile Tears - Quest
Gore Videos Uncensored
Hay day: Top 6 tips, tricks, and cheats to save cash and grow your farm fast!
Produzione mondiale di vino
Which aspects are important in sales |#1 Prospection
My.doculivery.com/Crowncork
Sotyktu Pronounce
2135 Royalton Road Columbia Station Oh 44028
Connexus Outage Map
180 Best Persuasive Essay Topics Ideas For Students in 2024
Non Sequitur
iLuv Aud Click: Tragbarer Wi-Fi-Lautsprecher für Amazons Alexa - Portable Echo Alternative
Samantha Lyne Wikipedia
How Much Is Tay Ks Bail
Tygodnik Polityka - Polityka.pl
Virginia New Year's Millionaire Raffle 2022
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Keci News
Happy Life 365, Kelly Weekers | 9789021569444 | Boeken | bol
The Old Way Showtimes Near Regency Theatres Granada Hills
All Breed Database
The Tower and Major Arcana Tarot Combinations: What They Mean - Eclectic Witchcraft
Sec Baseball Tournament Score
Haunted Mansion Showtimes Near Epic Theatres Of West Volusia
Studentvue Calexico
Vadoc Gtlvisitme App
Used Safari Condo Alto R1723 For Sale
Manuel Pihakis Obituary
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
Diana Lolalytics
Usf Football Wiki
KM to M (Kilometer to Meter) Converter, 1 km is 1000 m
Tugboat Information
Gpa Calculator Georgia Tech
2023 Nickstory
Flipper Zero Delivery Time
Valls family wants to build a hotel near Versailles Restaurant
Oklahoma City Farm & Garden Craigslist
Crystal Glassware Ebay
La Qua Brothers Funeral Home
Meet Robert Oppenheimer, the destroyer of worlds
Bismarck Mandan Mugshots
Google Flights Missoula
Edt National Board
Where To Find Mega Ring In Pokemon Radical Red
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6382

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.