diff --git a/source/fundamentals/crud/read-operations.txt b/source/fundamentals/crud/read-operations.txt index 60cf8425..ed477389 100644 --- a/source/fundamentals/crud/read-operations.txt +++ b/source/fundamentals/crud/read-operations.txt @@ -13,7 +13,9 @@ Read Operations Retrieve Data Count Documents Monitor Data Changes + /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` diff --git a/source/fundamentals/crud/read-operations/specify-documents-to-return.txt b/source/fundamentals/crud/read-operations/specify-documents-to-return.txt new file mode 100644 index 00000000..99e7d85f --- /dev/null +++ b/source/fundamentals/crud/read-operations/specify-documents-to-return.txt @@ -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() `: Specifies the maximum number of documents + to return from a query +- :ref:`Sort() `: Specifies the sort order for the returned documents +- :ref:`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 `. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` 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 ` + 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.Sort.Ascending()`` method to sort values from +lowest to highest, or the ``Builders.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>`_ \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/LimitSortSkip.cs b/source/includes/fundamentals/code-examples/LimitSortSkip.cs new file mode 100644 index 00000000..59faa74d --- /dev/null +++ b/source/includes/fundamentals/code-examples/LimitSortSkip.cs @@ -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 = ""; + + public static void Main(string[] args) + { + var mongoClient = new MongoClient(MongoConnectionString); + var database = mongoClient.GetDatabase("sample_restaurants"); + var collection = database.GetCollection("restaurants"); + + { + // start-limit + var filter = Builders.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.Filter.Eq("cuisine", "Italian"); + var sort = Builders.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.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.Filter.Eq("cuisine", "Italian"); + var sort = Builders.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 \ No newline at end of file