Docs HomeNode.js

Retrieve Data检索数据

Overview概述

You can use read operations to retrieve data from your MongoDB database. 您可以使用读取操作从MongoDB数据库中检索数据。There are multiple types of read operations that access the data in different ways. 有多种类型的读取操作以不同的方式访问数据。If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.如果您想根据现有数据集的一组标准请求结果,可以使用find()findOne()方法等find操作。

You can also further specify the information you are requesting by including additional parameters or by chaining other methods such as:您还可以通过包含其他参数或链接其他方法(如:

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 Cursor Fundamentals page.要了解如何检查存储在游标中的数据,请参阅游标基础知识页面

Find查找

You can call the find() method on a Collection object. 可以对Collection对象调用find()方法。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集合中的所有文档:

await myColl.find(); // no query
await 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 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 with an empty query parameter:例如,以下代码显示了如何在使用空查询参数执行查找操作时将投影指定为选项:

const options = {
projection: { _id: 0, field1: 1 },
};

const findResult = await myColl.findOne({}, options);

If you resolve the Promise returned by find(), you receive a reference to a Cursor with which you can navigate matched documents. 如果解析find()返回的Promise,则会收到一个对Cursor的引用,使用该引用可以导航匹配的文档。If you resolve the Promise returned by findOne(), you receive the matching document or null if there are no matches.如果解析findOne()返回的Promise,则会收到匹配的文档,如果没有匹配,则为null

Example

A pizza restaurant wants to find all pizzas ordered by Lemony Snicket yesterday. 一家披萨店想找到Lemony Snicket昨天点的所有披萨。They run the following find() query on the orders collection:他们对orders集合运行以下find()查询:

    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 a Cursor. You can print the documents retrieved using the for await...of syntax as shown below:一旦操作返回,findResult变量就会引用Cursor。您可以打印使用for await...of语法检索到的文档,如下所示:

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: ...},
...
]

See the find() and findOne() for fully-runnable examples.有关完全可运行的示例,请参阅find()findOne()

Aggregate聚合

If you want to run a custom processing pipeline to retrieve data from your database, you can use the aggregate() method. 如果要运行自定义处理管道从数据库中检索数据,可以使用aggregate()方法。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:他们对订单集合运行以下aggregate()查询,以获取每个不同“状态”字段的总数:

    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 a Cursor. 一旦操作返回,aggregateResult变量就会引用CursorYou can print the documents retrieved using the for await...of syntax as shown below:您可以打印使用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 }
]

See the MongoDB server manual pages on aggregation for more information on how to construct an aggregation pipeline.有关如何构建聚合管道的更多信息,请参阅有关聚合的MongoDB服务器手册页面。

Watch / Subscribe

You can use the watch() method to monitor a collection for changes to a collection that match certain criteria. 您可以使用watch()方法来监视集合是否对符合特定条件的集合进行了更改。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:为了实现这一点,他们创建了一个聚合管道来筛选插入操作并返回特定字段。他们将此管道传递给订单集合上调用的watch()方法,如下所示:

    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, see the change streams usage example.有关使用NodeJS驱动程序的watch()方法的可运行示例,请参阅更改流使用示例。