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()
方法等查找操作。
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¶
The 对引用要查询的集合的find()
method is called on the Collection
object that references the collection you want to query. 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 our guide on how to Specify a Query.有关如何指定查询文档的更多信息,请参阅我们的如何指定查询指南。
To access the results, you can optionally pass a callback in the method call or resolve the returned 要访问结果,可以选择在方法调用中传递回调或解析返回的Promise
object. Promise
对象。See our guide on Promises and Callbacks for more information.有关更多信息,请参阅我们的承诺和回调指南。
If you resolve the 如果解析Promise
returned by find()
, you receive a reference to a Cursor
with which you can navigate matched documents. find()
返回的承诺,则会收到对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 他们对orders集合运行以下find()
query on the orders
collection: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
. findResult
变量将引用Cursor
。You can print the documents retrieved using the 您可以使用forEach()
method as shown below:forEach()
方法打印检索到的文档,如下所示:
await cursor.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.有关完全可运行的示例,请参阅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 他们在orders集合上运行以下aggregate()
query on the orders
collection to fetch the totals for each distinct "status" field:aggregate()
查询,以获取每个不同“status”字段的总计:
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 您可以使用forEach()
method as shown below:forEach()
方法打印检索到的文档,如下所示:
await cursor.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 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 comands 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:orders
集合上调用的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()
方法的可运行示例,请参阅更改流用法示例。