On this page
Overview
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 Access Data From a Cursor 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.
Finding 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:
myColl.find(); // no query 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 that receives an empty query parameter:
const options = { projection: { _id: 0, field1: 1 }, }; const findResult = await myColl.findOne({}, options);
For more information about projecting document fields, see the Specify Which Fields to Return guide.
The find()
method returns a Cursor
instance from which you can
access the matched documents. The findOne()
method returns a Promise
instance, which you can resolve to access either the matching document or
a null
value 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:
// Search for orders by name and within a specific date range const findResult = 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 for await...of
syntax as shown below:
for await (const doc of findResult) { console.log(doc); }
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: ...}, ... ]
findOne() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Connect to MongoDB guide. This example
also uses the movies
collection in the sample_mflix
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
The following full file example finds a single document from the movies
collection. It uses the following parameters:
Filter that matches documents in which the
title
value is'The Room'
.Sort that organizes matched documents in descending order by rating, so if our query matches multiple documents the returned document will be the document with the highest rating.
Projection that explicitly excludes the
_id
field from returned documents and explicitly includes only thetitle
andimdb
object (and its embedded fields).
import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string. const uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Query for a movie that has the title 'The Room' const query = { title: "The Room" }; const options = { // Sort matched documents in descending order by rating sort: { "imdb.rating": -1 }, // Include only the `title` and `imdb` fields in the returned document projection: { _id: 0, title: 1, imdb: 1 }, }; // Execute query const movie = await movies.findOne(query, options); // Print the document returned by findOne() console.log(movie); } finally { await client.close(); } } run().catch(console.dir);
import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string. const uri = "<connection string uri>"; const client = new MongoClient(uri); interface IMDB { rating: number; votes: number; id: number; } export interface Movie { title: string; year: number; released: Date; plot: string; type: "movie" | "series"; imdb: IMDB; } type MovieSummary = Pick<Movie, "title" | "imdb">; async function run(): Promise<void> { try { const database = client.db("sample_mflix"); // Specifying a Schema is always optional, but it enables type hinting on // finds and inserts const movies = database.collection<Movie>("movies"); const movie = await movies.findOne<MovieSummary>( { title: "The Room" }, { sort: { rating: -1 }, projection: { _id: 0, title: 1, imdb: 1 }, } ); console.log(movie); } finally { await client.close(); } } run().catch(console.dir);
Running the preceding example results in the following output:
{ title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } }
find() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Connect to MongoDB guide. This example
also uses the movies
collection in the sample_mflix
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
The following full file example finds documents from the movies
collection. It
uses the following parameters:
Filter that matches documents in which the
runtime
value is less than 15 minutes.Sort that organizes returned documents in ascending order by title (alphabetical order in which "A" comes before "Z" and "1" before "9").
Projection that explicitly excludes the
_id
field from returned documents and explicitly includes only thetitle
andimdb
object (and its embedded fields).
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Query for movies that have a runtime less than 15 minutes 16 const query = { runtime: { $lt: 15 } }; 17 18 const options = { 19 // Sort returned documents in ascending order by title (A->Z) 20 sort: { title: 1 }, 21 // Include only the `title` and `imdb` fields in each returned document 22 projection: { _id: 0, title: 1, imdb: 1 }, 23 }; 24 25 // Execute query 26 const cursor = movies.find(query, options); 27 28 // Print a message if no documents were found 29 if ((await movies.countDocuments(query)) === 0) { 30 console.log("No documents found!"); 31 } 32 33 // Print returned documents 34 for await (const doc of cursor) { 35 console.dir(doc); 36 } 37 38 } finally { 39 await client.close(); 40 } 41 } 42 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 type Minutes = number; 9 10 interface IMDB { 11 rating: number; 12 votes: number; 13 id: number; 14 } 15 16 interface Movie { 17 title: string; 18 imdb: IMDB; 19 runtime: Minutes; 20 } 21 22 async function run() { 23 try { 24 const database = client.db("sample_mflix"); 25 const movies = database.collection<Movie>("movies"); 26 27 const query = { runtime: { $lt: 15 } }; 28 const cursor = movies.find<Movie>( 29 query, 30 { 31 sort: { title: 1 }, 32 projection: { _id: 0, title: 1, imdb: 1 }, 33 } 34 ); 35 36 if ((await movies.countDocuments(query)) === 0) { 37 console.warn("No documents found!"); 38 } 39 40 for await (const doc of cursor) { 41 console.dir(doc); 42 } 43 } finally { 44 await client.close(); 45 } 46 } 47 run().catch(console.dir);
Running the preceding example results in the following output:
{ title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } } { title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } } { title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } } { title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } } ...
You can also specify sort
and projection
options by chaining the
sort()
and projection
methods to the find()
method. The following
two commands are equivalent:
movies.find({ runtime: { $lt: 15 } }, { sort: { title: 1 }, projection: { _id: 0, title: 1, imdb: 1 }}); movies.find({ runtime: { $lt: 15 } }).sort({ title: 1}).project({ _id: 0, title: 1, imdb: 1 });
Additional Information
For more information about the findOne()
and find()
methods, see the
following Server manual documentation:
Aggregate Data from Documents
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:
// Group orders by status within the last week const aggregateResult = 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 for await...of
syntax as shown below:
for await (const doc of aggregateResult) { console.log(doc); }
The output might resemble the following:
[ { _id: 'delivering', count: 5 }, { _id: 'delivered', count: 37 }, { _id: 'created', count: 9 } ]
Additional Information
For more information on how to construct an aggregation pipeline, see the Aggregation guide or Aggregation Operations in the Server manual.
Monitor Data Changes
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:
// Set up a change stream to listen for new order insertions 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}.`); });
Additional Information
For a runnable example of the watch()
method, see the examples section in the Monitor Data Changes guide.