Retrieve Data检索数据
On this page本页内容
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:您还可以通过包含其他参数或链接其他方法(如:
Sort Results对结果排序Skip Returned Results跳过返回的结果Limit the Number of Returned Results限制返回结果的数量Specify Which Fields to Return指定要返回的字段
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.如果要监视数据库中是否存在与一组条件匹配的传入数据,则可以使用监视操作在插入匹配数据时实时收到通知。
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.有关如何指定查询文档的详细信息,请参阅指定查询指南。
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
。
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.使用这些表达式可以对集合中的结果数据进行筛选、分组和排列。
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
变量就会引用Cursor
。You 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.您可以向该方法传递聚合命令的管道,每当对集合执行写操作时,聚合命令就会在更改的数据上顺序运行。
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 有关使用NodeJS驱动程序的watch()
method using the NodeJS driver, see the change streams usage example.watch()
方法的可运行示例,请参阅更改流使用示例。