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
Domo Resource - Nine reasons why dashboard design is essential
How to convert Dai to xDai? - AlphaWallet
Sdn Md 2023-2024
Joi Databas
Skyward Houston County
Week 2 Defense (DEF) Streamers, Starters & Rankings: 2024 Fantasy Tiers, Rankings
No Limit Telegram Channel
Danatar Gym
Mopaga Game
The Best Classes in WoW War Within - Best Class in 11.0.2 | Dving Guides
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
Declan Mining Co Coupon
Robot or human?
Oppenheimer Showtimes Near Cinemark Denton
Job Shop Hearthside Schedule
Craigslist Farm And Garden Cincinnati Ohio
Costco Gas Foster City
Voy Boards Miss America
Schedule 360 Albertsons
Persona 5 Royal Fusion Calculator (Fusion list with guide)
Kashchey Vodka
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
Riherds Ky Scoreboard
Craigslistodessa
Jayah And Kimora Phone Number
JVID Rina sauce set1
CVS Health’s MinuteClinic Introduces New Virtual Care Offering
How rich were the McCallisters in 'Home Alone'? Family's income unveiled
Gncc Live Timing And Scoring
Kacey King Ranch
Grove City Craigslist Pets
La Qua Brothers Funeral Home
Was heißt AMK? » Bedeutung und Herkunft des Ausdrucks
Have you seen this child? Caroline Victoria Teague
Newsday Brains Only
Minecraft Jar Google Drive
Agematch Com Member Login
Skyrim:Elder Knowledge - The Unofficial Elder Scrolls Pages (UESP)
Main Street Station Coshocton Menu
What Does Code 898 Mean On Irs Transcript
Engr 2300 Osu
Gasoline Prices At Sam's Club
Sun Tracker Pontoon Wiring Diagram
Shoecarnival Com Careers
Garland County Mugshots Today
705 Us 74 Bus Rockingham Nc
Christie Ileto Wedding
El Patron Menu Bardstown Ky
Helpers Needed At Once Bug Fables
Charlotte North Carolina Craigslist Pets
Uncle Pete's Wheeling Wv Menu
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.