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 您可以执行查找操作以从MongoDB数据库中检索数据。您可以通过调用find() or findOne() method.find()或findOne()方法来执行查找操作,以根据一组条件匹配文档。
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.find()方法检索数据。您可以直接在浏览器窗口中完成此实验,而无需安装MongoDB或代码编辑器。
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:您可以使用Node.js驱动程序连接并执行以下环境中托管的部署的读取操作:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务 - MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
To learn more about performing read operations in the Atlas UI for deployments hosted in MongoDB Atlas, see View, Filter, and Sort Documents.要了解有关在MongoDB Atlas中托管的部署的Atlas UI中执行读取操作的更多信息,请参阅查看、筛选和排序文档。
Finding Documents查找文档
You can call the 您可以在Collection对象上调用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.find()方法。该方法接受描述要检索的文档的查询文档。有关如何指定查询文档的详细信息,请参阅《指定查询》指南。
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集合中的所有文档:
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.findOne()方法传递查询或传递空查询,则该操作将从集合中返回单个文档。
You can chain cursor methods to a find operation even when you pass an empty query. For example, the following code shows how you can specify a projection while performing a find operation that receives an empty query parameter:即使传递空查询,也可以将游标方法链接到查找操作。例如,以下代码显示了如何在执行接收空查询参数的查找操作时指定投影:
const projectFields = { _id: 0, field1: 1 };
const findResult = await myColl.findOne().project(projectFields);
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.find()方法返回一个Cursor实例,您可以从中访问匹配的文档。findOne()方法返回一个Promise实例,如果没有匹配项,您可以解析该实例以访问匹配的文档或null值。
Example示例
A pizza restaurant wants to find all pizzas ordered by Lemony Snicket yesterday. They run the following 一家披萨店想找到Lemony Snicket昨天订购的所有披萨。他们对find() query on the orders collection:orders集合运行以下find()查询:
// 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:findResult变量将引用Cursor。您可以使用for-await打印检索到的文档。语法如下:
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 FilefindOne()示例:完整文件
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. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
The following full file example finds a single document from the 以下完整文件示例从movies collection. It uses the following parameters:movies集合中查找单个文档。它使用以下参数:
Filter that matches documents in which the匹配titlevalue is'The Room'.title值为'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从返回的文档中显式排除_idfield from returned documents and explicitly includes only thetitleandimdbobject (and its embedded fields)._id字段并显式仅包含title和imdb对象(及其嵌入字段)的投影。
JavaScript
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
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在返回的文档中仅包含“title”和“imdb”字段
projection: { _id: 0, title: 1, imdb: 1 },
};
// Execute query执行查询
const movie = await movies.findOne(query, options);
// Print the document returned by findOne()打印findOne()返回的文档
console.log(movie);
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
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 Filefind()示例:完整文件
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. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
The following full file example finds documents from the 以下完整文件示例用于查找movies collection. It uses the following parameters:movies集合中的文档。它使用以下参数:
Filter that matches documents in which the匹配runtimevalue is less than 15 minutes.runtime(运行时)值小于15分钟的文档的筛选器。Sort that organizes returned documents in ascending order by title (alphabetical order in which "A" comes before "Z" and "1" before "9").按标题升序组织返回文档的排序(字母顺序为“A”在“Z”之前,“1”在“9”之前)。Projection that explicitly excludes the从返回的文档中显式排除_idfield from returned documents and explicitly includes only thetitleandimdbobject (and its embedded fields)._id字段并显式仅包含title和imdb对象(及其嵌入字段)的投影。
JavaScript
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
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 movies that have a runtime less than 15 minutes查询运行时间少于15分钟的电影
const query = { runtime: { $lt: 15 } };
const sortFields = { title: 1 };
const projectFields = { _id: 0, title: 1, imdb: 1 };
// Execute query 执行查询
const cursor = movies.find(query).sort(sortFields).project(projectFields);
// Print a message if no documents were found如果未找到文档,则打印消息
if ((await movies.countDocuments(query)) === 0) {
console.log("No documents found!");
}
// Print returned documents打印退回的文档
for await (const doc of cursor) {
console.dir(doc);
}
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
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);
type Minutes = number;
interface IMDB {
rating: number;
votes: number;
id: number;
}
interface Movie {
title: string;
imdb: IMDB;
runtime: Minutes;
}
async function run() {
try {
const database = client.db("sample_mflix");
const movies = database.collection<Movie>("movies");
const query = { runtime: { $lt: 15 } };
const sortFields = { title: 1 };
const projectFields = { _id: 0, title: 1, imdb: 1 };
const cursor = movies.find<Movie>(query).sort(sortFields).project(projectFields);
if ((await movies.countDocuments(query)) === 0) {
console.warn("No documents found!");
}
for await (const doc of cursor) {
console.dir(doc);
}
} finally {
await client.close();
}
}
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 } }
...
Note
You must chain a cursor method such as 在迭代游标之前,必须将游标方法(如sort(), limit(), skip(), or project() to a read operation before iterating the cursor. If you specify a cursor method after iterating the cursor, the setting does not apply to the read operation.sort()、limit()、skip()或project())链接到读取操作。如果在迭代游标后指定游标方法,则该设置不适用于读取操作。
Additional Information附加信息
For more information about the 有关findOne() and find() methods, see the following Server manual documentation:findOne()和find()方法的更多信息,请参阅以下服务器手册文档:
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.aggregate()方法。此方法接受按顺序运行的聚合表达式。这些表达式允许您筛选、分组和排列集合中的结果数据。
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:aggregate()查询,以获取每个不同“状态”字段的总计:
// 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:aggregateResult变量就会引用Cursor。您可以使用for await...of语法打印检索到的文档。语法如下:
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 Operations 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.watch()方法监视集合中符合特定条件的集合更改。这些更改包括插入、更新、替换和删除的文档。您可以向此方法传递一个聚合命令管道,每当对集合执行写入操作时,该管道都会在更改的数据上顺序运行。
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:watch()方法,如下所示:
// 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 with Change Streams guide.watch()方法的可运行示例,请参阅《使用更改流监视数据》指南中的示例部分。