Retrieve Data检索数据

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:您还可以通过包括其他参数或链接其他方法(如:

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

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

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. 一旦操作返回,findResult变量将引用CursorYou 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()

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:他们在orders集合上运行以下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变量将引用CursorYou 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服务器手册中有关聚合的页面。

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.您可以向此方法传递聚合命令的管道,每当对集合执行写入操作时,该管道都会在更改的数据上顺序运行。

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:它们将此管道传递给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 watch() method using the NodeJS driver, see the change streams usage example.有关使用NodeJS驱动程序的watch()方法的可运行示例,请参阅更改流用法示例。