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
Open Change Streams </fundamentals/crud/read-operations/change-streams>
Search Text </fundamentals/crud/read-operations/text-search>
Sort Data </fundamentals/crud/read-operations/sort>
Skip Results </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 @@ -152,7 +152,8 @@ The following table describes commonly used settings that you can specify in
| 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 @@ -394,8 +395,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
147 changes: 147 additions & 0 deletions source/fundamentals/crud/read-operations/skip.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
.. _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/skip.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/skip.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.

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-example:

Query Results Example
~~~~~~~~~~~~~~~~~~~~~

To skip documents, you can initialize a ``FindOptions`` instance and specify the
number of documents you want to skip using the ``skip()`` method. Then, pass
your ``FindOptions`` struct as a parameter to the ``find()`` method.

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-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": ObjectId("..."), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
Document({"_id": ObjectId("..."), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})
Document({"_id": ObjectId("..."), "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>`__
1 change: 1 addition & 0 deletions source/fundamentals/crud/read-operations/sort.txt
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ To learn more about the operations mentioned in this guide, see the following:
- :ref:`rust-retrieve-guide`
- :ref:`rust-compound-operations`
- :ref:`rust-aggregation`
- :ref:`rust-skip-guide`

API Documentation
~~~~~~~~~~~~~~~~~
Expand Down
79 changes: 79 additions & 0 deletions source/includes/fundamentals/code-snippets/crud/skip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use std::env;
use mongodb::{ bson::doc, 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 {
name: "The Brothers Karamazov".to_string(),
author: "Dostoyevsky".to_string(),
length: 824,
},
Book {
name: "Atlas Shrugged".to_string(),
author: "Rand".to_string(),
length: 1088,
},
Book {
name: "Les Misérables".to_string(),
author: "Hugo".to_string(),
length: 1462,
},
Book {
name: "A Dance with Dragons".to_string(),
author: "Martin".to_string(),
length: 1104,
},
];

my_coll.insert_many(books, None).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 find_options = FindOptions::builder()
.sort(doc! { "author": 1 })
.skip(2)
.build();
let mut cursor = my_coll.find(doc! {}, find_options).await?;

while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
// end-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, None).await?;

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

Ok(())
}
Loading