Docs Home / Node.js Driver

Specify Documents to Return指定要返回的文档

Overview概述

In this guide, you can learn how to specify which documents to return from a read operation by using the following methods:在本指南中,您可以学习如何使用以下方法指定从读取操作返回哪些文档:

  • sort(): Specifies the sort order for the returned documents.:指定返回文档的排序顺序。
  • limit(): Specifies the maximum number of documents to return from a query.:指定查询返回的最大文档数。
  • skip(): Specifies the number of documents to skip before returning query results.:指定在返回查询结果之前要跳过的文档数。

Sample Data for Examples示例数据示例

To run the examples in this guide, use the following code snippet to insert documents that describe books into the myDB.books collection:要运行本指南中的示例,请使用以下代码片段将描述书籍的文档插入到myDB.books集合中:

const myDB = client.db("myDB");
const myColl = myDB.collection("books");

await myColl.insertMany([
{ "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 },
{ "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 },
{ "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 },
{ "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 },
{ "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 },
{ "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 },
]);

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())链接到读取操作。如果在迭代游标后指定游标方法,则该设置不适用于读取操作。

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.您的查询操作可能会返回对包含匹配文档的游标的引用。要了解如何检查存储在游标中的数据,请参阅“从游标访问数据”页面。

Sort排序

Use the sort() method to change the order in which read operations return documents. This method tells MongoDB to order returned documents by the values of one or more fields in a certain direction. To sort returned documents by a field in ascending (lowest first) order, use a value of 1. To sort in descending (greatest first) order instead, use -1. If you do not specify a sort, MongoDB does not guarantee the order of query results.使用sort()方法更改读取操作返回文档的顺序。此方法告诉MongoDB按照某个方向上一个或多个字段的值对返回的文档进行排序。要按字段升序(从低到高)对返回的文档进行排序,请使用值1。要改为按降序(最大优先)排序,请使用-1。如果不指定排序,MongoDB不保证查询结果的顺序。

The following example passes the sort document to a read operation to ensure that the operation returns books with longer lengths before books with shorter lengths:以下示例将排序文档传递给读取操作,以确保该操作返回长度较长的书籍,然后返回长度较短的书籍:

// define an empty query document定义一个空查询文档
const query = {};
// sort in descending (-1) order by length按长度降序(-1)排序
const sortFields = { length: -1 };
const cursor = myColl.find(query).sort(sortFields);
for await (const doc of cursor) {
console.dir(doc);
}

In this case, the number -1 tells the read operation to sort the books in descending order by length. find() returns the following documents when this sort is used with an empty query:在这种情况下,数字-1告诉读取操作按长度降序对书籍进行排序。当此排序与空查询一起使用时,find()返回以下文档:

{ "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
{ "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
{ "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 }
{ "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 }
{ "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
{ "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }

Sometimes, the order of two or more documents is ambiguous using a specified sort. In the preceding example, the documents that have title values of "A Dance with Dragons" and "Infinite Jest" both have a length of 1104, so the order in which they are returned is not guaranteed. To resolve ties in your sorted results in a repeatable way, add more fields to the sort document:有时,使用指定的排序时,两个或多个文档的顺序是模糊的。在前面的例子中,title值为"A Dance with Dragons"(“与龙共舞”)和"Infinite Jest"(“无限恶作剧”)的文档都有1104length(长度),因此无法保证它们返回的顺序。要以可重复的方式解决排序结果中的关系,请在排序文档中添加更多字段:

// define an empty query document定义一个空查询文档
const query = {};
// sort in ascending (1) order by length按长度升序(1)排序
const sortFields = { length: 1, author: 1 };
const cursor = myColl.find(query).sort(sortFields);
for await (const doc of cursor) {
console.dir(doc);
}

With the addition of the author field to the sort document, the read operation sorts matching documents first by length then, if there is a tie, by author. Matched document fields are compared in the same order as fields are specified in the sort document. 在排序文档中添加author字段后,读取操作将首先按length(长度)对匹配的文档进行排序,如果有联系,则按作者进行排序。匹配的文档字段按照与排序文档中指定的字段相同的顺序进行比较。find() returns the following ordering of documents when this sort is used on the documents matching the query:当对与查询匹配的文档使用此排序时,find()返回以下文档顺序:

{ "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }
{ "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
{ "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 }
{ "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 }
{ "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
{ "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }

Limit限制

Use the limit() method to cap the number of documents that can be returned from a read operation. This method specifies the maximum number of documents that the operation can return, but the operation can return a smaller number of documents if there are not enough documents present to reach the limit. If limit() is used with the skip() method, the skip applies first and the limit only applies to the documents left over after the skip.使用limit()方法限制读取操作可以返回的文档数量。此方法指定操作可以返回的最大文档数,但如果没有足够的文档达到限制,则操作可以返回较少的文档数。如果limit()skip()方法一起使用,则跳过首先应用,限制仅适用于跳过后留下的文档。

This example performs the following actions:此示例执行以下操作:

  • Uses an empty query filter to match all documents in the collection使用空查询筛选器来匹配集合中的所有文档
  • Calls the sort() method to apply a descending sort on the length field to the results调用sort()方法对结果的length字段应用降序排序
  • Calls the limit() method to return only the first 3 results调用limit()方法仅返回前3个结果
// define an empty query document定义一个空查询文档
const query = {};
// sort in descending (-1) order by length按长度降序(-1)排序
const sortFields = { length: -1 };
const limitNum = 3;
const cursor = myColl.find(query).sort(sortFields).limit(limitNum);
for await (const doc of cursor) {
console.dir(doc);
}

The code example above outputs the following three documents, sorted by length:上面的代码示例输出以下三个文档,按长度排序:

{ "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
{ "_id": 6, "title": "A Dance With Dragons", "author": "Martin", "length": 1104 }
{ "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }

Note

The order in which you call limit() and sort() does not matter because the driver reorders the calls to apply the sort first. The following two calls are equivalent:调用limit()sort()的顺序并不重要,因为驱动程序会重新排序调用以首先应用排序。以下两个调用是等效的:

myColl.find(query).sort({ length: -1 }).limit(3);
myColl.find(query).limit(3).sort({ length: -1 });

Skip跳过

Use the skip() method to omit documents from the beginning of the read operation results. You can combine skip() with sort() to omit the top (for descending order) or bottom (for ascending order) results for a given query. 使用skip()方法从读取操作结果的开头省略文档。您可以将skip()sort()结合使用,以省略给定查询的顶部(降序)或底部(升序)结果。Since the order of documents returned is not guaranteed in the absence of a sort, using skip() without using sort() omits arbitrary documents.由于在没有排序的情况下无法保证返回文档的顺序,因此使用skip()而不使用sort()可以省略任意文档。

If the value of skip() exceeds the number of matched documents for a query, then that query returns no documents.如果skip()的值超过查询的匹配文档数,则该查询不返回任何文档。

This example queries the collection for the books with the fifth and sixth highest lengths by performing the following actions:此示例通过执行以下操作查询集合中长度第五和第六高的书籍:

  • Uses an empty query filter to match all documents in the collection使用空查询筛选器来匹配集合中的所有文档
  • Calls the sort() method to apply a descending sort to the length field, which returns longer books before shorter books调用sort()方法对length字段应用降序排序,该字段在返回较短书籍之前返回较长书籍
  • Calls the skip() method to omit the first four matching documents from the result调用skip()方法从结果中省略前四个匹配的文档
// define an empty query document定义一个空查询文档
const query = {};
const sortFields = { length: -1 };
const skipNum = 4;
const cursor = myColl.find(query).sort(sortFields).skip(skipNum);
for await (const doc of cursor) {
console.dir(doc);
}

Since the query skips the first four matching documents, the preceding code snippet prints the fifth and sixth highest length documents:由于查询跳过了前四个匹配的文档,因此前面的代码片段将打印第五个和第六个最长的文档:

{ "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
{ "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }

Combine Limit, Sort, and Skip组合限制、排序和跳过

You can combine the limit, sort, and skip options in a single operation. This allows you to set a maximum number of sorted documents to return, skipping a specified number of documents before returning.您可以在单个操作中组合limitsortskip选项。这允许您设置要返回的已排序文档的最大数量,在返回之前跳过指定数量的文档。

The following example returns documents with the length value of "1104". The results are sorted in alphabetical order, skipping the first document and includes only the first result:以下示例返回length值为“1104”的文档。结果按字母顺序排序,跳过第一个文档,仅包含第一个结果:

const query = {length: "1104"};

const cursor = myColl.find(query).sort({ title: 1 }).skip(1).limit(1);

for await (const doc of cursor) {
console.dir(doc);
}
{ "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }

Note

The order in which you call these methods doesn't change the documents that are returned.调用这些方法的顺序不会改变返回的文档。

Additional Information附加信息

For more information about specifying a query, see Query Operations.有关指定查询的详细信息,请参阅查询操作

For more information about retrieving documents, see Find Documents.有关检索文档的详细信息,请参阅查找文档

API Documentation文档

To learn more about any of the methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何方法的更多信息,请参阅以下API文档: