Skip to content

DOCSP-45005: Specify Docs to Return #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 19, 2024
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
2 changes: 2 additions & 0 deletions source/fundamentals/crud/read-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ Read Operations
Retrieve Data </fundamentals/crud/read-operations/retrieve>
Count Documents </fundamentals/crud/read-operations/count>
Monitor Data Changes </fundamentals/crud/read-operations/change-streams>
/fundamentals/crud/read-operations/specify-documents-to-return

- :ref:`csharp-retrieve`
- :ref:`csharp-count-documents`
- :ref:`csharp-change-streams`
- :ref:`csharp-specify-documents-to-return`
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
.. _csharp-specify-documents-to-return:

===========================
Specify Documents to Return
===========================

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

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

.. meta::
:keywords: read, paginate, pagination, order, code example

Overview
--------

In this guide, you can learn how to specify which documents to return
from a read operation by chaining the following methods to the ``Find()``
method:

- :ref:`Limit() <csharp-return-documents-limit>`: Specifies the maximum number of documents
to return from a query
- :ref:`Sort() <csharp-return-documents-sort>`: Specifies the sort order for the returned documents
- :ref:`Skip() <csharp-return-documents-skip>`: Specifies the number of documents to skip before
returning query results

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide.

The examples on this page use the following ``Restaurant`` class as a model for the
documents in the collection:

.. literalinclude:: /includes/fundamentals/code-examples/LimitSortSkip.cs
:start-after: start-restaurant-class
:end-before: end-restaurant-class
:language: csharp

.. _csharp-return-documents-limit:

Limit
-----

To specify the maximum number of documents returned from a read operation, use
the ``Limit()`` method provided by the ``IFindFluent`` interface. After calling
the ``Find()`` method, chain the ``Limit()`` method to modify the behavior of the
operation.

The following example finds all restaurants that have a ``cuisine`` field value
of ``"Italian"`` and limits the results to ``5`` documents:

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

.. input:: /includes/fundamentals/code-examples/LimitSortSkip.cs
:start-after: start-limit
:end-before: end-limit
:language: csharp
:dedent:

.. output::
:visible: false

V & T Restaurant
Mimis Restaurant & Bar
Venice Restaurant
Areo Restaurant
Tre Giovani Pizza & Pasta

.. tip::

The preceding example returns the first five documents matched by the query
according to their :manual:`natural order </reference/glossary/#std-term-natural-order>`
in the database. The following section describes how to return the documents
in a specified order.

.. _csharp-return-documents-sort:

Sort
----

To return documents in a specified order, use the ``Sort()`` method provided by
the ``IFindFluent`` interface. After calling the ``Find()`` method, chain the ``Sort()``
method to modify the behavior of the operation.

When calling ``Sort()``, you must pass in the sort definition as a parameter. You can construct a sort
definition by using the ``Builders<T>.Sort.Ascending()`` method to sort values from
lowest to highest, or the ``Builders<T>.Sort.Ascending()`` method to sort them from highest
to lowest. Both of these methods take the field name to sort by as a parameter. These methods
can be chained to sort returned documents by multiple fields.

The following example returns all documents that have a ``cuisine`` field value
of ``"Italian"``, sorted in ascending order of ``name`` field values:

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

.. input:: /includes/fundamentals/code-examples/LimitSortSkip.cs
:start-after: start-sort
:end-before: end-sort
:language: csharp
:dedent:

.. output::
:visible: false

(Lewis Drug Store) Locanda Vini E Olii
101 Restaurant And Bar
44 Sw Ristorante & Bar
900 Park
A Voce
...

.. _csharp-return-documents-skip:

Skip
----

To skip a specified number of documents before returning your query results, use
the ``Skip()`` method provided by the ``IFindFluent`` interface. After calling
the ``Find()`` method, chain the ``Skip()`` method to modify the behavior of the
operation.

The following example returns all documents that have a ``cuisine`` field value
of ``"Italian"`` and skips the first ``10`` documents:

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

.. input:: /includes/fundamentals/code-examples/LimitSortSkip.cs
:start-after: start-skip
:end-before: end-skip
:language: csharp
:dedent:

.. output::
:visible: false

Trattoria Alba
Da Umberto Restaurant
La Strada Restaurant
Pasta Lovers Trattoria
Nanni Restaurant
Villa Mosconi Restaurant
Villa Berulia
Marco Polo Ristorante
Cafe Luna
Baraonda

.. _csharp-return-documents-combine:

Combine Limit, Sort, and Skip
-----------------------------

You can chain the ``Limit()``, ``Sort()``, and ``Skip()`` methods to a single
``Find()`` method call. This allows you to set a maximum number of sorted documents
to return from the read operation, skipping a specified number of documents before
returning.

The following example returns ``5`` documents that have a ``cuisine`` value of
``"Italian"``. The results are sorted in ascending order by the ``name`` field value,
skipping the first ``10`` documents:

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

.. input:: /includes/fundamentals/code-examples/LimitSortSkip.cs
:start-after: start-limit-sort-skip
:end-before: end-limit-sort-skip
:language: csharp
:dedent:

.. output::
:visible: false

Acqua
Acqua Restaurant
Acqua Santa
Acquista Trattoria
Acquolina Catering
Adriatic Restaurant Pizzeria Bar
Adrienne'S Pizza Bar
Ai Fiori
Aita Restaurant
Al Di La

.. note::

The order in which you call these methods doesn't change the documents
that are returned. The {+driver-short+} automatically reorders the calls to
perform the sort operation first, the skip operation next, and then the limit
operation.

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

For more information about retrieving documents, see the :ref:`csharp-retrieve` guide.

For more information about specifying a query, see the :ref:`csharp-specify-query` guide.

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

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

- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`_
- `IFindFluent <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluent-2.html>`_
- `Limit() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluent-2.Limit.html>`_
- `Sort() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluent-2.Sort.html>`_
- `Skip() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluent-2.Skip.html>`_
81 changes: 81 additions & 0 deletions source/includes/fundamentals/code-examples/LimitSortSkip.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;

public class LimitSortSkip
{
// Replace with your connection string
private const string MongoConnectionString = "<connection string URI>";

public static void Main(string[] args)
{
var mongoClient = new MongoClient(MongoConnectionString);
var database = mongoClient.GetDatabase("sample_restaurants");
var collection = database.GetCollection<Restaurant>("restaurants");

{
// start-limit
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Italian");
var results = collection.Find(filter).Limit(5).ToList();

foreach (var result in results)
{
Console.WriteLine(result.Name);
}
// end-limit
}

{
// start-sort
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Italian");
var sort = Builders<Restaurant>.Sort.Ascending("name");
var results = collection.Find(filter).Sort(sort).ToList();

foreach (var result in results)
{
Console.WriteLine(result.Name);
}
// end-sort
}

{
// start-skip
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Italian");
var results = collection.Find(filter).Skip(10).ToList();

foreach (var result in results)
{
Console.WriteLine(result.Name);
}
// end-skip
}

{
// start-limit-sort-skip
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Italian");
var sort = Builders<Restaurant>.Sort.Ascending("name");

var results = collection.Find(filter).Limit(10).Sort(sort).Skip(10).ToList();

foreach (var result in results)
{
Console.WriteLine(result.Name);
}
// end-limit-sort-skip
}
}
}

// start-restaurant-class
[BsonIgnoreExtraElements]
public class Restaurant {
public ObjectId Id { get; set; }

[BsonElement("name")]
public string Name { get; set; }

[BsonElement("cuisine")]
public string Cuisine { get; set; }
}
// end-restaurant-class
Loading