@@ -20,21 +20,23 @@ a query, that query returns no documents.
20
20
Follow the instructions in the examples below to insert data into
21
21
a collection and perform a sort and skip on the results of a query.
22
22
Consider a collection containing documents that describe varieties of
23
- fruit. To insert this data into a collection, run the following
24
- operation:
23
+ fruit:
25
24
26
25
.. code-block:: javascript
27
26
28
- await collection.insertMany( [
27
+ [
29
28
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
30
29
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
31
30
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
32
31
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
33
- ]);
32
+ ]
34
33
35
- Pass the following sort document to a read operation to ensure that the
36
- operation returns fruit documents with higher ratings before fruit
37
- documents with lower ratings:
34
+ In the following example, we query the collection with a filter that
35
+ matches all the documents and pass options that specifies ``sort`` and
36
+ ``skip`` commands as query options. The sort option specifies that fruit
37
+ documents with higher ratings should be returned before ones with lower
38
+ ratings. The skip option specifies that the first 2 documents should be
39
+ omitted from the result:
38
40
39
41
.. code-block:: javascript
40
42
@@ -50,12 +52,20 @@ documents with lower ratings:
50
52
const cursor = collection.find(query, options);
51
53
await cursor.forEach(console.dir);
52
54
53
- In this case, the number ``-1`` tells the read operation to sort the
54
- fruit in descending order by rating. ``skip`` omits the first two
55
- matched documents in the sorted order. ``find()`` returns the following
56
- documents when this sort is used with an empty query:
55
+ Since we specified that the first ``2`` documents should be skipped, the
56
+ third and fourth highest rating documents are printed by the code snippet
57
+ above:
57
58
58
59
.. code-block:: javascript
59
60
60
61
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }
61
62
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 }
63
+
64
+
65
+ The ``sort`` and ``skip`` options can also be specified as methods chained to
66
+ the ``find`` method. The following two commands are equivalent:
67
+
68
+ .. code-block:: javascript
69
+
70
+ collection.find(query, { sort: { rating: -1}, skip: 2});
71
+ collection.find(query).sort({rating: -1}).skip(2);
0 commit comments