Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions source/fundamentals/crud/read-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ Read Operations
/fundamentals/crud/read-operations/change-streams
/fundamentals/crud/read-operations/text-search
/fundamentals/crud/read-operations/sort
/fundamentals/crud/read-operations/skip

..
/fundamentals/crud/read-operations/count
/fundamentals/crud/read-operations/distinct
/fundamentals/crud/read-operations/skip
/fundamentals/crud/read-operations/limit
/fundamentals/crud/read-operations/project

Expand All @@ -28,11 +28,12 @@ Read Operations
- :ref:`rust-change-streams-guide`
- :ref:`rust-search-text-guide`
- :ref:`rust-sort-guide`
- :ref:`rust-skip-guide`

.. - :ref:`rust-query-guide`
.. - :ref:`rust-count-guide`
.. - :ref:`rust-distinct-guide`

.. - :ref:`rust-skip-guide`

.. - :ref:`rust-limit-guide`
.. - :ref:`rust-project-guide`
6 changes: 3 additions & 3 deletions source/fundamentals/crud/read-operations/retrieve.txt
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ fields that you can set by calling their corresponding builder methods:
| Type: ``ReadConcern``

* - ``skip``
- | The number of documents to skip when returning results.
- | The number of documents to skip when returning results. To learn more
about how to use the ``skip()`` builder method, see :ref:`rust-skip-guide`.
|
| Type: ``u64``
| Default: ``None``
Expand Down Expand Up @@ -388,8 +389,7 @@ following documentation:
- :ref:`rust-cursor-guide` guide
- :ref:`rust-aggregation` guide
- :ref:`rust-sort-guide` guide

.. - :ref:`rust-skip-guide`
- :ref:`rust-skip-guide` guide

.. - :ref:`rust-limit-guide`
.. - :ref:`rust-project-guide`
Expand Down
187 changes: 187 additions & 0 deletions source/fundamentals/crud/read-operations/skip.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
.. _rust-skip-guide:

=====================
Skip Returned Results
=====================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code example, read operation, skip, skip results

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to use the {+driver-long+} to perform a read
operation that skips a specified number of documents when returning results.

Sample Data for Examples
------------------------

The examples in this guide use the following ``Book`` struct as a model for
documents in the ``books`` collection:

.. literalinclude:: /includes/fundamentals/code-snippets/crud/sort.rs
:start-after: start-book-struct
:end-before: end-book-struct
:language: rust
:dedent:

The following code shows how to insert sample data into the ``books``
collection:

.. literalinclude:: /includes/fundamentals/code-snippets/crud/sort.rs
:start-after: start-sample-data
:end-before: end-sample-data
:language: rust
:dedent:

Skip Documents
--------------

You can skip results retrieved by a query, or you can skip results within an
aggregation pipeline.

This section describes how to skip results in the following ways:

- :ref:`skip() method <rust-skip-method>`: Chain the ``skip()`` method to the
``find()`` method
- :ref:`FindOptions struct <rust-findoptions-skip>`: Use the ``skip()`` option
builder method to configure a ``FindOptions`` struct
- :ref:`Aggregation pipleline <rust-aggregation-skip>`: Create a pipeline that uses the ``$skip`` stage

If the number of skipped documents exceeds the number of matched documents for a
query, then that query returns no documents.

Find operations return documents in a natural order that is not sorted on any
fields. To avoid skipping random documents, use the ``sort()`` method to sort
documents on a field with a unique value before setting a skip option. To learn
more, see the :ref:`rust-sort-guide` guide.

.. _rust-skip-method:

skip() Method Example
~~~~~~~~~~~~~~~~~~~~~~

To skip documents, you can chain the ``skip()`` method to the ``find()`` method.
The ``skip()`` method takes an integer that specifies the number of documents to
omit from the beginning of the result set.

This example runs a ``find()`` operation that performs the following actions:

- Sorts the results in ascending order of their ``author`` field values
- Skips the first two documents
- Returns the remaining documents

.. io-code-block::
:copyable: true

.. input:: /includes/fundamentals/code-snippets/crud/skip.rs
:start-after: start-skip-example
:end-before: end-skip-example
:language: rust
:dedent:

.. output::
:language: console
:visible: false

Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }

.. _rust-findoptions-skip:

Options Example
~~~~~~~~~~~~~~~

Alternatively, if you are setting and reusing options for your query, you can
use ``FindOptions``. Set the ``skip`` field of the ``FindOptions`` struct by
using the ``skip()`` option builder method. Then, chain the ``with_options()``
method to the ``find()`` method and pass your ``FindOptions`` struct as a
parameter to the ``with_options()`` method.

This example runs a ``find()`` operation that performs the following actions:

- Sorts the results in descending order of their ``name`` field values
- Skips the first document
- Returns the remaining documents

.. io-code-block::
:copyable: true

.. input:: /includes/fundamentals/code-snippets/crud/skip.rs
:start-after: start-options-skip-example
:end-before: end-options-skip-example
:language: rust
:dedent:

.. output::
:language: console
:visible: false

Book { name: "Les Misérables", author: "Hugo", length: 1462 }
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }

.. _rust-aggregation-skip:

Aggregation Example
~~~~~~~~~~~~~~~~~~~

You can use the ``$skip`` stage in an aggregation pipeline to skip documents. To
learn more about aggregation operations, see the :ref:`rust-aggregation` guide.

This example runs an aggregation pipeline that performs the following actions:

- Sorts the results in ascending order of their ``author`` field values
- Skips the first document
- Returns the remaining documents

.. io-code-block::
:copyable: true

.. input:: /includes/fundamentals/code-snippets/crud/skip.rs
:start-after: start-aggregation-example
:end-before: end-aggregation-example
:language: rust
:dedent:

.. output::
:language: console
:visible: false

Document({"_id": Int32(3), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
Document({"_id": Int32(4), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})
Document({"_id": Int32(2), "name": String("Atlas Shrugged"), "author": String("Rand"), "length": Int32(1088)})

Additional Information
----------------------

To learn more about the operations mentioned in this guide, see the following guides:

- :ref:`rust-query-guide`
- :ref:`rust-retrieve-guide`
- :ref:`rust-compound-operations`
- :ref:`rust-aggregation`
- :ref:`rust-sort-guide`
.. - :ref:`rust-limit-guide`

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this guide, see the
following API documentation:

- `find() <{+api+}/struct.Collection.html#method.find>`__
- `FindOptions <{+api+}/options/struct.FindOptions.html>`__
- `FindOneOptions <{+api+}/options/struct.FindOneOptions.html>`__
- `Cursor <{+api+}/struct.Cursor.html>`__
- `aggregate() <{+api+}/struct.Collection.html#method.aggregate>`__
- `AggregateOptions <{+api+}/options/struct.AggregateOptions.html>`__
5 changes: 3 additions & 2 deletions source/fundamentals/crud/read-operations/sort.txt
Original file line number Diff line number Diff line change
Expand Up @@ -182,18 +182,19 @@ The following example specifies a descending sort on the ``name`` field:
Additional Information
----------------------

To learn more about the operations metnioned in this guide, see the following:
To learn more about the operations mentioned in this guide, see the following:

- :ref:`rust-query-guide`
- :ref:`rust-retrieve-guide`
- :ref:`rust-compound-operations`
- :ref:`rust-aggregation`
- :ref:`rust-skip-guide`

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this guide, see the
following API Documentation:
following API documentation:

- `find() <{+api+}/struct.Collection.html#method.find>`__
- `FindOptions <{+api+}/options/struct.FindOptions.html>`__
Expand Down
97 changes: 97 additions & 0 deletions source/includes/fundamentals/code-snippets/crud/skip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use std::env;
use mongodb::{ bson::doc, bson::Document, Client, Collection, options::FindOptions };
use serde::{Deserialize, Serialize};
use futures::stream::TryStreamExt;

// start-book-struct
#[derive(Debug, Serialize, Deserialize)]
struct Book {
name: String,
author: String,
length: i32,
}
// end-book-struct

#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// start-sample-data
let uri = "connection string";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Book> = client.database("db").collection("books");

let books = vec![
Book {
id: 1,
name: "The Brothers Karamazov".to_string(),
author: "Dostoyevsky".to_string(),
length: 824,
},
Book {
id: 2,
name: "Atlas Shrugged".to_string(),
author: "Rand".to_string(),
length: 1088,
},
Book {
id: 3,
name: "Les Misérables".to_string(),
author: "Hugo".to_string(),
length: 1462,
},
Book {
id: 4,
name: "A Dance with Dragons".to_string(),
author: "Martin".to_string(),
length: 1104,
},
];

my_coll.insert_many(books).await?;
// end-sample-data

// Retrieves documents in the collection, sorts results by their "author" field
// values, and skips the first two results.
// start-skip-example
let mut cursor = my_coll
.find(doc! {})
.sort(doc! { "author": 1 })
.skip(2).await?;

while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
// end-skip-example

// Sets the values for the `FindOptions` struct to sort results by their "name"
// field values, skip the first two results, and return the remaining results.
// start-options-skip-example
let find_options = FindOptions::builder()
.sort(doc! { "name": -1 })
.skip(1)
.build();

let mut cursor = my_coll.find(doc! {}).with_options(find_options).await?;

while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
// end-options-skip-example

// Retrieves documents in the collection, sorts results by their "author" field,
// then skips the first two results in an aggregation pipeline.
// start-aggregation-example
let pipeline = vec![
doc! { "$match": {} },
doc! { "$sort": { "author": 1 } }
doc! { "$skip": 1 },
];

let mut cursor = my_coll.aggregate(pipeline).await?;

while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
// end-aggregation-example

Ok(())
}
2 changes: 1 addition & 1 deletion source/includes/fundamentals/code-snippets/crud/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ while let Some(result) = cursor.try_next().await? {

// start-sort-aggregation
let pipeline = vec![
docs! { "$match": {} },
doc! { "$match": {} },
// 1 for ascending order, -1 for descending order
doc! { "$sort": { "author": 1 } }
];
Expand Down
Loading