diff --git a/config/intersphinx.yaml b/config/intersphinx.yaml index 5cad55e4..3e317721 100644 --- a/config/intersphinx.yaml +++ b/config/intersphinx.yaml @@ -1,4 +1,4 @@ -# Weirdly, giza wants a non-empty list of two or more, so we have to include extraneous/unused one --hence the python +# Weirdly, giza wants a non-empty list of two or more, so we must include extraneous/unused one --hence the python name: python url: https://docs.python.org/2/ path: python2.inv diff --git a/config/redirects b/config/redirects index 9351a914..05bf9565 100644 --- a/config/redirects +++ b/config/redirects @@ -23,3 +23,76 @@ raw: ${prefix}/master -> ${base}/upcoming/ [*-v2.30]: ${prefix}/${version}/fundamentals/odata/ -> ${base}/${version}/ [*-v2.30]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk-write/ -> ${base}/${version}/fundamentals/crud/write-operations/ [v2.22-v2.24]: ${prefix}/${version}/fundamentals/authentication/oidc/ -> ${base}/${version}/fundamentals/authentication/ + +# comprehensive coverage reorg +[*-master]: ${prefix}/${version}/fundamentals/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/fundamentals/connection/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/fundamentals/crud/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/usage-examples/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/get-started/create-connection-string/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/get-started/deploy-cluster/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/get-started/download-driver/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/get-started/run-sample-query/ -> ${base}/${version}/get-started/ +[*-master]: ${prefix}/${version}/compatibility/ -> ${base}/${version}/reference/compatibility/ +[*-master]: ${prefix}/${version}/previous-versions/ -> ${base}/${version}/reference/previous-versions/ +[*-master]: ${prefix}/${version}/quick-reference/ -> ${base}/${version}/reference/quick-reference/ +[*-master]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/reference/release-notes/ +[*-master]: ${prefix}/${version}/upgrade/ -> ${base}/${version}/reference/upgrade/ +[*-master]: ${prefix}/${version}/upgrade/v2/ -> ${base}/${version}/reference/upgrade/v2/ +[*-master]: ${prefix}/${version}/upgrade/v3/ -> ${base}/${version}/reference/upgrade/v3/ +[*-master]: ${prefix}/${version}/fundamentals/linq/ -> ${base}/${version}/aggregation/ +[*-master]: ${prefix}/${version}/fundamentals/aggregation/ -> ${base}/${version}/aggregation/ +[*-master]: ${prefix}/${version}/fundamentals/odata/ -> ${base}/${version}/integrations/odata/ +[*-master]: ${prefix}/${version}/fundamentals/indexes/ -> ${base}/${version}/indexes/ +[*-master]: ${prefix}/${version}/fundamentals/atlas-search/ -> ${base}/${version}/atlas-search/ +[*-master]: ${prefix}/${version}/fundamentals/builders/ -> ${base}/${version}/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connection-options/ -> ${base}/${version}/connect/connection-options/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connection-pools/ -> ${base}/${version}/connect/connection-options/connection-pools/ +[*-master]: ${prefix}/${version}/fundamentals/connection/network-compression/ -> ${base}/${version}/connect/connection-options/network-compression/ +[*-master]: ${prefix}/${version}/fundamentals/connection/server-selection/ -> ${base}/${version}/connect/connection-options/server-selection/ +[*-master]: ${prefix}/${version}/fundamentals/connection/connect/ -> ${base}/${version}/connect/mongoclient/ +[*-master]: ${prefix}/${version}/fundamentals/connection/tls/ -> ${base}/${version}/security/tls-ssl/ +[*-master]: ${prefix}/${version}/fundamentals/read-write-configuration/ -> ${base}/${version}/crud/configure/ +[*-master]: ${prefix}/${version}/connection-troubleshooting/ -> ${base}/${version}/connect/connection-troubleshooting/ +[*-master]: ${prefix}/${version}/fundamentals/geo/ -> ${base}/${version}/crud/geo/ +[*-master]: ${prefix}/${version}/fundamentals/stable-api/ -> ${base}/${version}/connect/connection-options/stable-api/ +[*-master]: ${prefix}/${version}/fundamentals/gridfs/ -> ${base}/${version}/crud/gridfs/ +[*-master]: ${prefix}/${version}/fundamentals/specify-query/ -> ${base}/${version}/crud/query/specify-query/ +[*-master]: ${prefix}/${version}/fundamentals/transactions/ -> ${base}/${version}/crud/transactions/ +[*-master]: ${prefix}/${version}/fundamentals/bson/ -> ${base}/${version}/document-formats/bson/ +[*-master]: ${prefix}/${version}/fundamentals/time-series/ -> ${base}/${version}/time-series/ +[*-master]: ${prefix}/${version}/fundamentals/logging/ -> ${base}/${version}/logging-and-monitoring/logging/ +[*-master]: ${prefix}/${version}/fundamentals/monitoring/ -> ${base}/${version}/logging-and-monitoring/monitoring/ +[*-master]: ${prefix}/${version}/fundamentals/database-collection/ -> ${base}/${version}/databases-collections/ +[*-master]: ${prefix}/${version}/fundamentals/encrypt-fields/ -> ${base}/${version}/security/in-use-encryption/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/distinct/ -> ${base}/${version}/crud/query/distinct/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/retrieve/ -> ${base}/${version}/crud/query/find/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/project/ -> ${base}/${version}/crud/query/project/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/specify-documents-to-return/ -> ${base}/${version}/crud/query/specify-documents-to-return/ +[*-master]: ${prefix}/${version}/fundamentals/crud/read-operations/change-streams/ -> ${base}/${version}/logging-and-monitoring/change-streams/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/insert/ -> ${base}/${version}/crud/insert/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/delete/ -> ${base}/${version}/crud/delete/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/bulk-write/ -> ${base}/${version}/bulk-write/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/replace/ -> ${base}/${version}/crud/replace/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-many/ -> ${base}/${version}/crud/update-many/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-many/arrays/ -> ${base}/${version}/crud/update-many/arrays/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-many/fields/ -> ${base}/${version}/crud/update-many/fields/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-one/ -> ${base}/${version}/crud/update-one/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-one/arrays/ -> ${base}/${version}/crud/update-one/arrays/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/update-one/fields/ -> ${base}/${version}/crud/update-one/fields/ +[*-master]: ${prefix}/${version}/fundamentals/serialization/class-mapping/ -> ${base}/${version}/serialization/class-mapping/ +[*-master]: ${prefix}/${version}/fundamentals/serialization/poco/ -> ${base}/${version}/serialization/poco/ +[*-master]: ${prefix}/${version}/fundamentals/serialization/polymorphic-objects/ -> ${base}/${version}/serialization/polymorphic-objects/ +[*-master]: ${prefix}/${version}/fundamentals/serialization/ -> ${base}/${version}/serialization/ +[*-master]: ${prefix}/${version}/fundamentals/databases-collections/run-command/ -> ${base}/${version}/run-command/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/ -> ${base}/${version}/security/authentication/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/aws-iam/ -> ${base}/${version}/security/authentication/aws-iam/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/kerberos/ -> ${base}/${version}/security/authentication/kerberos/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/ldap/ -> ${base}/${version}/security/authentication/ldap/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/oidc/ -> ${base}/${version}/security/authentication/oidc/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/scram/ -> ${base}/${version}/security/authentication/scram/ +[*-master]: ${prefix}/${version}/fundamentals/authentication/x509/ -> ${base}/${version}/security/authentication/x509/ +[*-master]: ${prefix}/${version}/crud/query/specify-documents-to-return/ -> ${base}/${version}/crud/query/specify-documents/ +[*-master]: ${prefix}/${version}/crud/query/specify-query/ -> ${base}/${version}/crud/query/query-filter/ diff --git a/snooty.toml b/snooty.toml index 638b4c24..dd4bad46 100644 --- a/snooty.toml +++ b/snooty.toml @@ -1,15 +1,11 @@ toc_landing_pages = [ - "/fundamentals/connection", - "/fundamentals/crud", - "/usage-examples", - "/fundamentals", - "/fundamentals/serialization", - "/fundamentals/crud/write-operations/update-one", - "/fundamentals/crud/write-operations/update-many", - "/fundamentals/authentication", - "/upgrade", - "/fundamentals/database-collection", - "/fundamentals/indexes", + "/get-started", + "/connect/connection-options", + "/security/authentication", + "/aggregation", + "/aggregation/stages", + "/serialization", + "/indexes", ] name = "csharp" title = "C#/.NET Driver" @@ -50,4 +46,4 @@ not-available = "N/A" analyzer = "MongoDB C# Analyzer" analyzer-short = "C# Analyzer" query-api = "MongoDB Query API" -vector-search = "Atlas Vector Search" +avs = "Atlas Vector Search" diff --git a/source/aggregation.txt b/source/aggregation.txt new file mode 100644 index 00000000..5fd99c22 --- /dev/null +++ b/source/aggregation.txt @@ -0,0 +1,119 @@ +.. _csharp-aggregation: + +====================== +Aggregation Operations +====================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: dotnet, code example, transform, pipeline + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Pipeline Stages + LINQ + +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to perform +**aggregation operations**. + +Aggregation operations process data in your MongoDB collections and +return computed results. The MongoDB Aggregation framework is modeled on the +concept of data processing pipelines. Documents enter a pipeline comprised of one or +more stages, and this pipeline transforms the documents into an aggregated result. + +To learn more about the aggregation stages supported by the {+driver-short+}, see +:ref:`Aggregation Stages `. + +.. sharedinclude:: dbx/agg-tutorials-manual-tip.rst + + .. replacement:: language + + :guilabel:`{+language+}` + +Analogy +~~~~~~~ + +Aggregation operations function similarly to car factories with assembly +lines. The assembly lines have stations with specialized tools to +perform specific tasks. For example, when building a car, the assembly +line begins with the frame. Then, as the car frame moves through the +assembly line, each station assembles a separate part. The result is a +transformed final product, the finished car. + +The assembly line represents the *aggregation pipeline*, the individual +stations represent the *aggregation stages*, the specialized tools +represent the *expression operators*, and the finished product +represents the *aggregated result*. + +Compare Aggregation and Find Operations +--------------------------------------- + +The following table lists the different tasks you can perform with find +operations, compared to what you can achieve with aggregation +operations. The aggregation framework provides expanded functionality +that allows you to transform and manipulate your data. + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Find Operations + - Aggregation Operations + + * - | Select *certain* documents to return + | Select *which* fields to return + | Sort the results + | Limit the results + | Count the results + - | Select *certain* documents to return + | Select *which* fields to return + | Sort the results + | Limit the results + | Count the results + | Group the results + | Rename fields + | Compute new fields + | Summarize data + | Connect and merge data sets + +Server Limitations +------------------ + +Consider the following :manual:`limitations ` when +performing aggregation operations: + +- Returned documents must not violate the :manual:`BSON document size limit ` + of 16 megabytes. + +- Pipeline stages have a memory limit of 100 megabytes by default. If required, you can exceed this limit by setting + the `AllowDiskUse <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AggregateOptions.AllowDiskUse.html#MongoDB_Driver_AggregateOptions_AllowDiskUse>`__ + property of the ``AggregateOptions`` object that you pass to the ``Aggregate()`` method. + +Troubleshooting +--------------- + +.. include:: /includes/troubleshooting/unsupported-filter-expression.rst + +Additional Information +---------------------- + +To view a full list of expression operators, see +:manual:`Aggregation Operators `. + +To learn about explaining MongoDB aggregation operations, see +:manual:`Explain Results ` and +:manual:`Query Plans `. diff --git a/source/fundamentals/linq.txt b/source/aggregation/linq.txt similarity index 99% rename from source/fundamentals/linq.txt rename to source/aggregation/linq.txt index 73c5ffcc..94be8a2c 100644 --- a/source/fundamentals/linq.txt +++ b/source/aggregation/linq.txt @@ -1,5 +1,8 @@ .. _csharp-linq: +====================================== +LINQ Syntax for Aggregation Operations +====================================== ====================================== LINQ Syntax for Aggregation Operations ====================================== @@ -36,7 +39,7 @@ The {+driver-short+} automatically translates LINQ queries into The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets `. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, -see the :ref:``. +see :ref:``. The following ``Restaurant``, ``Address`` and ``GradeEntry`` classes model the documents in this collection: @@ -1025,7 +1028,7 @@ aggregation stages: - ``$out`` To learn how to create an aggregation pipeline with the ``$out`` stage by using Builders, see -the :ref:`` section. +:ref:``. Supported Methods ----------------- diff --git a/source/aggregation/stages.txt b/source/aggregation/stages.txt new file mode 100644 index 00000000..df593041 --- /dev/null +++ b/source/aggregation/stages.txt @@ -0,0 +1,363 @@ +.. _csharp-aggregation-stages: +.. _csharp-builders-aggregation: + +=========================== +Aggregation Pipeline Stages +=========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: dotnet, code example, transform, pipeline + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +On this page, you can learn how to create an aggregation pipeline and pipeline stages +by using methods in the {+driver-short+}. + +Build an Aggregation Pipeline +----------------------------- + +You can use the {+driver-short+} to build an aggregation pipeline by using builder +methods or BSON documents. See the following sections to learn more about each of these +approaches. + +.. _csharp-aggregation-stages-builder: + +Builder Methods +~~~~~~~~~~~~~~~ + +You can build a type-safe aggregation pipeline in the following ways: + +- Construct an ``EmptyPipelineDefinition`` object. Chain calls from this object + to the relevant aggregation methods. Then, pass the pipeline object to the + ``IMongoCollection.Aggregate()`` method. + +- Call the ``IMongoCollection.Aggregate()`` method. Chain calls from this + method call to the relevant aggregation methods. + +Select the :guilabel:`EmptyPipelineDefinition` +or :guilabel:`Aggregate` tab to see the corresponding code for each approach: + +.. tabs:: + + .. tab:: EmptyPipelineDefinition + :tabid: empty-pipeline-definition + + .. code-block:: csharp + + // Defines the aggregation pipeline + var pipeline = new EmptyPipelineDefinition() + .Match(...) + .Group(...) + .Merge(...); + + // Executes the aggregation pipeline + var results = collection.Aggregate(pipeline); + + .. tab:: Aggregate + :tabid: aggregate + + .. code-block:: csharp + + // Defines and executes the aggregation pipeline + var results = collection.Aggregate() + .Match(...) + .Group(...) + .Merge(...); + +.. _csharp-aggregation-stages-bsondocument: + +BsonDocument +~~~~~~~~~~~~ + +Some aggregation stages don't have corresponding methods in the {+driver-short+}. +To add these stages to your pipeline, use ``BsonDocument`` objects or string literals +to construct a stage in the Query API syntax. Then, pass the BSON document to the +``PipelineDefinitionBuilder.AppendStage()`` method. This syntax supports all stages +in the aggregation pipeline, but doesn't provide type hints or type safety. + +The following code example shows how to add the ``$unset`` stage to an empty aggregation +pipeline: + +.. code-block:: csharp + + var pipeline = new EmptyPipelineDefinition() + .AppendStage("{ $unset: 'field1' }"); + +.. important:: + + If you use a ``BsonDocument`` to define a pipeline stage, the driver doesn't + recognize any ``BsonClassMap`` attributes, serialization attributes, or + serialization conventions. The field names that you use in the ``BsonDocument`` must + match the field names stored in {+mdb-server+}. + +Aggregation Stage Methods +------------------------- + +The following table lists the builder methods in the {+driver-short+} that correspond +to stages in the aggregation pipeline. To learn more about an aggregation stage and +see a code example for the equivalent C# method, follow the link from the stage name +to its reference page in the {+mdb-server+} manual. + +If an aggregation stage isn't in the table, the driver doesn't provide a builder method for +it. In this case, you must use the +:ref:`BsonDocument ` syntax to add the stage +to your pipeline. + +.. list-table:: + :header-rows: 1 + :widths: 28 44 28 + + * - Aggregation Stage + - Description + - Builder Method + + * - :manual:`$bucket ` + - Categorizes incoming documents into groups, called buckets, + based on a specified expression and bucket boundaries. + - ``Bucket()`` + + * - :manual:`$bucketAuto ` + - Categorizes incoming documents into a specific number of + groups, called buckets, based on a specified expression. + Bucket boundaries are automatically determined in an attempt + to evenly distribute the documents into the specified number + of buckets. + - ``BucketAuto()`` + + * - :manual:`$changeStream ` + - Returns a change stream cursor for the + collection. This stage can occur only once in an aggregation + pipeline and it must occur as the first stage. + - ``ChangeStream()`` + + * - :manual:`$changeStreamSplitLargeEvent ` + - Splits large change stream events that exceed 16 MB into smaller fragments returned + in a change stream cursor. + + You can use ``$changeStreamSplitLargeEvent`` only in a ``$changeStream`` pipeline, and + it must be the final stage in the pipeline. + - ``ChangeStreamSplitLargeEvent()`` + + * - :manual:`$count ` + - Returns a count of the number of documents at this stage of + the aggregation pipeline. + - ``Count()`` + + * - :manual:`$densify ` + - Creates new documents in a sequence of documents where certain values in a field are missing. + - ``Densify()`` + + * - :manual:`$documents ` + - Returns literal documents from input expressions. + - ``Documents()`` + + * - :manual:`$facet ` + - Processes multiple aggregation pipelines + within a single stage on the same set + of input documents. Enables the creation of multi-faceted + aggregations capable of characterizing data across multiple + dimensions, or facets, in a single stage. + - ``Facet()`` + + * - :manual:`$geoNear ` + - Returns documents in order of nearest to farthest from a + specified point. This method adds a field to output documents + that contains the distance from the specified point. + - ``GeoNear()`` + + * - :manual:`$graphLookup ` + - Performs a recursive search on a collection. This method adds + a new array field to each output document that contains the traversal + results of the recursive search for that document. + - ``GraphLookup()`` + + * - :manual:`$group ` + - Groups input documents by a specified identifier expression + and applies the accumulator expressions, if specified, to + each group. Consumes all input documents and outputs one + document per each distinct group. The output documents + contain only the identifier field and, if specified, accumulated + fields. + - ``Group()`` + + * - :manual:`$limit ` + - Passes the first *n* documents unmodified to the pipeline, + where *n* is the specified limit. For each input document, + outputs either one document (for the first *n* documents) or + zero documents (after the first *n* documents). + - ``Limit()`` + + * - :manual:`$lookup ` + - Performs a left outer join to another collection in the + *same* database to filter in documents from the "joined" + collection for processing. + - ``Lookup()`` + + * - :manual:`$match ` + - Filters the document stream to allow only matching documents + to pass unmodified into the next pipeline stage. + For each input document, outputs either one document (a match) or zero + documents (no match). + - ``Match()`` + + * - :manual:`$merge ` + - Writes the resulting documents of the aggregation pipeline to + a collection. The stage can incorporate (insert new + documents, merge documents, replace documents, keep existing + documents, fail the operation, process documents with a + custom update pipeline) the results into an output + collection. To use this stage, it must be + the last stage in the pipeline. + - ``Merge()`` + + * - :manual:`$out ` + - Writes the resulting documents of the aggregation pipeline to + a collection. To use this stage, it must be + the last stage in the pipeline. + - ``Out()`` + + * - :manual:`$project ` + - Reshapes each document in the stream, such as by adding new + fields or removing existing fields. For each input document, + outputs one document. + - ``Project()`` + + * - :manual:`$rankFusion ` + - Uses a rank fusion algorithm to combine results from a Vector Search + query and an Atlas Search query. + - ``RankFusion()`` + + * - :manual:`$replaceRoot ` + - Replaces a document with the specified embedded document. The + operation replaces all existing fields in the input document, + including the ``_id`` field. Specify a document embedded in + the input document to promote the embedded document to the + top level. + + The ``$replaceWith`` stage is an alias for the ``$replaceRoot`` stage. + - ``ReplaceRoot()`` + + * - :manual:`$replaceWith ` + - Replaces a document with the specified embedded document. + The operation replaces all existing fields in the input document, including + the ``_id`` field. Specify a document embedded in the input document to promote + the embedded document to the top level. + + The ``$replaceWith`` stage is an alias for the ``$replaceRoot`` stage. + - ``ReplaceWith()`` + + * - :manual:`$sample ` + - Randomly selects the specified number of documents from its + input. + - ``Sample()`` + + * - :manual:`$search ` + - Performs a full-text search of the field or fields in an + :atlas:`Atlas ` + collection. + + This stage is available only for MongoDB Atlas clusters, and is not + available for self-managed deployments. To learn more, see + :atlas:`Atlas Search Aggregation Pipeline Stages + ` in the Atlas documentation. + - ``Search()`` + + * - :manual:`$searchMeta ` + - Returns different types of metadata result documents for the + :atlas:`Atlas Search ` query against an + :atlas:`Atlas ` + collection. + + This stage is available only for MongoDB Atlas clusters, + and is not available for self-managed deployments. To learn + more, see :atlas:`Atlas Search Aggregation Pipeline Stages + ` in the Atlas documentation. + - ``SearchMeta()`` + + * - :manual:`$set ` + - Adds new fields to documents. Like the ``Project()`` method, + this method reshapes each + document in the stream by adding new fields to + output documents that contain both the existing fields + from the input documents and the newly added fields. + - ``Set()`` + + * - :manual:`$setWindowFields ` + - Groups documents into windows and applies one or more + operators to the documents in each window. + - ``SetWindowFields()`` + + * - :manual:`$skip ` + - Skips the first *n* documents, where *n* is the specified skip + number, and passes the remaining documents unmodified to the + pipeline. For each input document, outputs either zero + documents (for the first *n* documents) or one document (if + after the first *n* documents). + - ``Skip()`` + + * - :manual:`$sort ` + - Reorders the document stream by a specified sort key. The documents remain unmodified. + For each input document, outputs one document. + - ``Sort()`` + + * - :manual:`$sortByCount ` + - Groups incoming documents based on the value of a specified + expression, then computes the count of documents in each + distinct group. + - ``SortByCount()`` + + * - :manual:`$unionWith ` + - Combines pipeline results from two collections into a single + result set. + - ``UnionWith()`` + + * - :manual:`$unwind ` + - Deconstructs an array field from the input documents to + output a document for *each* element. Each output document + replaces the array with an element value. For each input + document, outputs *n* Documents, where *n* is the number of + array elements. *n* can be zero for an empty array. + - ``Unwind()`` + + * - :manual:`$vectorSearch ` + - Performs an :abbr:`ANN (Approximate Nearest Neighbor)` or + :abbr:`ENN (Exact Nearest Neighbor)` search on a + vector in the specified field of an + :atlas:`Atlas ` collection. + + This stage is available only for MongoDB Atlas clusters, and is not + available for self-managed deployments. To learn more, see + :ref:`Atlas Vector Search `. + - ``VectorSearch()`` + +API Documentation +----------------- + +To learn more about assembling an aggregation pipeline, see +:manual:`Aggregation Pipeline ` in the {+mdb-server+} +manual. + +To learn more about creating pipeline stages, see +:manual:`Aggregation Stages ` in the +{+mdb-server+} manual. + +For more information about the methods and classes used on this page, see the +following API documentation: + +- `Aggregate() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.Aggregate.html>`__ +- `AggregateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AggregateOptions.html>`__ +- `EmptyPipelineDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.EmptyPipelineDefinition-1.-ctor.html>`__ +- `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ +- `PipelineDefinitionBuilder.AppendStage() + <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineDefinitionBuilder.AppendStage.html>`__ diff --git a/source/fundamentals/atlas-search.txt b/source/atlas-search.txt similarity index 97% rename from source/fundamentals/atlas-search.txt rename to source/atlas-search.txt index 536ec60a..13900a77 100644 --- a/source/fundamentals/atlas-search.txt +++ b/source/atlas-search.txt @@ -38,7 +38,7 @@ To learn more about the ``$search`` pipeline stage, see :manual:`$search The examples in this guide use the following documents in a collection called ``guitars``: -.. code-block:: text +.. code-block:: json { "_id": 1, "make": "Fender", "description": "Classic guitars known for their versatility.", "establishedYear": 1946, "in_stock": true, "rating": 9 } { "_id": 2, "make": "Gibson", "description": "Classic guitars known for their rich, full tones.", "establishedYear": 1902, "in_stock": true, "rating": 8 } @@ -69,7 +69,7 @@ Create an Atlas Search Index Before you can perform a search on an Atlas collection, you must first create an **Atlas Search index** on the collection. An Atlas Search index is a data structure that -categorizes data in a searchable format. +categorizes data in a searchable format. To learn how to create an Atlas Search Index see the :atlas:`Create an Atlas Search Index ` Atlas guide. @@ -110,11 +110,11 @@ field for text that starts with the string ``"Gib"``. The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } -To learn more about the ``autocomplete`` operator, see the :atlas:`autocomplete ` +To learn more about the ``autocomplete`` operator, see the :atlas:`autocomplete ` Atlas guide. Compound @@ -124,7 +124,7 @@ Use the ``Compound()`` method to combine two or more operators into a single search. The following example searches the ``guitars`` collection for any documents -that match all of the following criteria: +that match all the following criteria: - The ``rating`` field exists on the document - The ``in_stock`` field is not ``false`` @@ -138,13 +138,13 @@ that match all of the following criteria: The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "...", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 3, "make" : "PRS", "description" : "...", "establishedYear" : 1985, "in_stock" : true, "rating" : 9 } { "_id" : 5, "make" : "Ibanez", "description" : "...", "establishedYear" : 1957, "in_stock" : true, "rating" : 7 } -To learn more about the ``compound`` operator, see the :atlas:`compound ` +To learn more about the ``compound`` operator, see the :atlas:`compound ` Atlas guide. EmbeddedDocument @@ -155,7 +155,7 @@ within a field's array value. .. note:: - To search on embedded documents, you must create an + To search on embedded documents, you must create an ``embeddedDocument`` index on the array field. To learn how to define an ``embeddedDocument`` index, see @@ -188,7 +188,7 @@ and returns any documents with a ``serial`` field value of ``"YZ5678"``: The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9, "productDetails" : [{ "product_id" : 1234, "serial" : "YZ5678" }] } @@ -212,7 +212,7 @@ which the value of the ``in_stock`` field is ``true``. The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "...", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "...", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } @@ -220,7 +220,7 @@ The search returns the following documents: { "_id" : 5, "make" : "Ibanez", "description" : "...", "establishedYear" : 1957, "in_stock" : true, "rating" : 7 } -To learn more about the ``equals`` operator, see the :atlas:`equals ` +To learn more about the ``equals`` operator, see the :atlas:`equals ` Atlas guide. Exists @@ -241,7 +241,7 @@ which the ``rating`` field exists. The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "...", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "...", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } @@ -302,7 +302,7 @@ Consider some documents in the ``guitars`` collection have added an follows: .. code-block:: json - + { "_id": 1, "make": "Fender", "description": "...", "establishedYear": 1946, "in_stock": true, "in_stock_location": { "type": "Point", "coordinates": [ -73.93615, 40.69791 ]}, "rating": 9 } { "_id": 2, "make": "Gibson", "description": "...", "establishedYear": 1902, "in_stock": true, "in_stock_location": { "type": "Point", "coordinates": [ 47.6062, 122.321 ]}, "rating": 8 } @@ -318,11 +318,11 @@ polygon: The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "...", "establishedYear" : 1946, "in_stock" : true, "in_stock_location" : { "type" : "Point", "coordinates" : ["-73.93615", "40.69791"] }, "rating" : 9 } -To learn more about the ``geoShape`` operator, see the :atlas:`geoShape ` +To learn more about the ``geoShape`` operator, see the :atlas:`geoShape ` Atlas guide. GeoWithin @@ -348,13 +348,13 @@ Consider some documents in the ``guitars`` collection have added an follows: .. code-block:: json - + { "_id": 1, "make": "Fender", "description": "...", "establishedYear": 1946, "in_stock": true, "in_stock_location": { "type": "Point", "coordinates": [ -73.93615, 40.69791 ]}, "rating": 9 } { "_id": 2, "make": "Gibson", "description": "...", "establishedYear": 1902, "in_stock": true, "in_stock_location": { "type": "Point", "coordinates": [ 47.6062, 122.321 ]}, "rating": 8 } The following example searches for all documents in which the coordinates in the ``in_stock_location`` field falls within a specified -polygon: +polygon: .. literalinclude:: /includes/fundamentals/code-examples/atlas-search/AtlasSearchExamples.cs :start-after: // start-geowithin-search @@ -364,11 +364,11 @@ polygon: The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "in_stock_location" : { "type" : "Point", "coordinates" : ["-73.93615", "40.69791"] }, "rating" : 9 } -To learn more about the ``geoWithin`` operator, see the :atlas:`geoWithin ` +To learn more about the ``geoWithin`` operator, see the :atlas:`geoWithin ` Atlas guide. In @@ -388,7 +388,7 @@ The following example searches the ``guitars`` collection for documents that hav The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id": 1, "make": "Fender", "description": "...", "establishedYear": 1946, "in_stock": true, "rating": 9 } { "_id": 2, "make": "Gibson", "description": "...", "establishedYear": 1902, "in_stock": true, "rating": 8 } @@ -411,13 +411,13 @@ quality." The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 3, "make" : "PRS", "description" : "High-end guitars known for their quality.", "establishedYear" : 1985, "in_stock" : true, "rating" : 9 } { "_id" : 4, "make" : "Kiesel", "description" : "Quality guitars made only for custom orders.", "establishedYear" : 2015, "in_stock" : false, "rating" : null } -To learn more about the ``moreLikeThis`` operator, see the :atlas:`moreLikeThis ` +To learn more about the ``moreLikeThis`` operator, see the :atlas:`moreLikeThis ` Atlas guide. Near @@ -442,7 +442,7 @@ order based on how close the value is to the number ``9``. The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "...", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 3, "make" : "PRS", "description" : "...", "establishedYear" : 1985, "in_stock" : true, "rating" : 9 } @@ -450,7 +450,7 @@ The search returns the following documents: { "_id" : 5, "make" : "Ibanez", "description" : "...", "establishedYear" : 1957, "in_stock" : true, "rating" : 7 } -To learn more about the ``near`` operator, see the :atlas:`near ` +To learn more about the ``near`` operator, see the :atlas:`near ` Atlas guide. Phrase @@ -470,7 +470,7 @@ the ``description`` field contains the phrase "classic guitars." The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } @@ -486,13 +486,13 @@ phrases as follows: This search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 4, "make" : "Kiesel", "description" : "Quality guitars made only for custom orders.", "establishedYear" : 2015, "in_stock" : false, "rating" : null } { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } -To learn more about the ``phrase`` operator, see the :atlas:`phrase ` +To learn more about the ``phrase`` operator, see the :atlas:`phrase ` Atlas guide. QueryString @@ -502,7 +502,7 @@ Use the ``QueryString()`` method to search for documents using a string with the following operators and delimiters: - ``AND`` -- ``OR`` +- ``OR`` - ``NOT`` - ``()`` @@ -520,13 +520,13 @@ the value of the ``description`` field matches each of the following criteria: The search returns the following documents: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 3, "make" : "PRS", "description" : "High-end guitars known for their quality.", "establishedYear" : 1985, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } -To learn more about the ``queryString`` operator, see the :atlas:`queryString ` +To learn more about the ``queryString`` operator, see the :atlas:`queryString ` Atlas guide. Range @@ -546,7 +546,7 @@ an ``establishedYear`` value greater than 1980 and less than 2020. The search returns the following results: -.. code-block:: text +.. code-block:: json { "_id" : 3, "make" : "PRS", "description" : "High-end guitars known for their quality.", "establishedYear" : 1985, "in_stock" : true, "rating" : 9 } { "_id" : 4, "make" : "Kiesel", "description" : "Quality guitars made only for custom orders.", "establishedYear" : 2015, "in_stock" : false, "rating" : null } @@ -571,7 +571,7 @@ to ``"Kiesel"``. The driver compares the string values in :wikipedia:`lexicograp The search returns the following results: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } @@ -597,7 +597,7 @@ the value of the ``make`` field contains exactly six letters. The search returns the following results: -.. code-block:: text +.. code-block:: json { "_id" : 1, "make" : "Fender", "description" : "Classic guitars known for their versatility.", "establishedYear" : 1946, "in_stock" : true, "rating" : 9 } { "_id" : 2, "make" : "Gibson", "description" : "Classic guitars known for their rich, full tones.", "establishedYear" : 1902, "in_stock" : true, "rating" : 8 } @@ -620,7 +620,7 @@ The search returns the following results: search results. To learn more, see :atlas:`regex Behavior `. -To learn more about the ``regex`` operator, see the :atlas:`regex ` +To learn more about the ``regex`` operator, see the :atlas:`regex ` Atlas guide. Span @@ -647,7 +647,7 @@ the value of the ``description`` field contains the strings "guitars" and The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 4, "make" : "Kiesel", "description" : "Quality guitars made only for custom orders.", "establishedYear" : 2015, "in_stock" : false, "rating" : null } @@ -655,7 +655,7 @@ Although the document with ``_id: 3`` contains the strings "guitars" and "quality", they are separated by more than one word, so the search omits this document from the results. -To learn more about the ``span`` operator, see the :atlas:`span ` +To learn more about the ``span`` operator, see the :atlas:`span ` Atlas guide. Text @@ -677,7 +677,7 @@ professionals". The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 5, "make" : "Ibanez", "description" : "Well-crafted guitars used by many professional guitarists.", "establishedYear" : 1957, "in_stock" : true, "rating" : 7 } @@ -686,7 +686,7 @@ The search returns the following document: If your search string contains multiple terms, the method also looks for a match for each term in the string separately. -To learn more about the ``text`` operator, see the :atlas:`text ` +To learn more about the ``text`` operator, see the :atlas:`text ` Atlas guide. Wildcard @@ -702,7 +702,7 @@ characters in your search: * - Character - Description - + * - ``?`` - Matches any single character @@ -723,7 +723,7 @@ field contains the string "Strand" followed by any other characters. The search returns the following document: -.. code-block:: text +.. code-block:: json { "_id" : 6, "make" : "Strandberg", "description" : "Modern guitars known for their headless models.", "establishedYear" : 1982, "in_stock" : false, "rating" : null } @@ -743,7 +743,7 @@ The search returns the following document: search results. To learn more, see :atlas:`wildcard Behavior `. -To learn more about the ``wildcard`` operator, see the :atlas:`wildcard ` +To learn more about the ``wildcard`` operator, see the :atlas:`wildcard ` Atlas guide. Search Multiple Fields diff --git a/source/fundamentals/builders.txt b/source/atlas-vector-search.txt similarity index 51% rename from source/fundamentals/builders.txt rename to source/atlas-vector-search.txt index 14aeef19..0d9bb208 100644 --- a/source/fundamentals/builders.txt +++ b/source/atlas-vector-search.txt @@ -1,460 +1,202 @@ -.. _csharp-builders: +.. _csharp-atlas-vector-search: -======================== -Operations with Builders -======================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol +================================ +Run an Atlas Vector Search Query +================================ .. facet:: :name: genre :values: reference .. meta:: - :keywords: aggregation, query, code example - :description: Learn to use builders in the .NET/C# Driver for MongoDB to create filters, projections, sorts, updates, and index keys, ensuring compile-time safety. + :keywords: .NET, search, semantic, AI, RAG + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol Overview -------- -In this guide, you can learn about the helper classes, or **builders**, that -the {+driver-short+} provides to create types used in your operations. -Using builders helps you identify errors at compile time and avoid them -at runtime. This guide provides information on builder classes that you -can use for the following tasks: +You can use {+avs+} to perform vector search on your data stored in +Atlas. Vector search allows you to query your data based on semantic meaning +rather than just keyword matches, which helps you retrieve more relevant search +results. It enables your AI-powered applications to support use cases such as +semantic search, hybrid search, and generative search, including +Retrieval-Augmented Generation (RAG). -- Creating a filter definition -- Creating a projection -- Defining a sort order -- Defining an update operation -- Selecting index keys +By using Atlas as a vector database, you can seamlessly index vector data along +with your other data in Atlas. This allows you to filter on fields in your +collection and perform vector search queries against vector data. You can also +combine vector search with full-text search queries to return the most relevant +results for your use case. You can integrate {+avs+} with popular AI +frameworks and services to easily implement vector search in your applications. -.. tip:: {+analyzer+} +To learn more about {+avs+}, see the :atlas:`{+avs+} +` guide in the MongoDB Atlas +documentation. - The {+analyzer-short+} is a tool that helps you analyze your - builders definitions and understand how your {+lang-framework+} code - translates into the {+query-api+}. For more information and - installation instructions, see the `{+analyzer-short+} reference page `__. +Sample Data +~~~~~~~~~~~ -You should read this guide if you want to learn more about how to -construct definitions and build up syntax using builders. +The examples in this guide use the ``sample_mflix.embedded_movies`` collection +in the ``sample_mflix`` database. To obtain the sample dataset for this collection, +see :ref:`csharp-get-started`. -Sample Class ------------- +The examples in this guide use the following sample class to model documents in the +``sample_mflix.embedded_movies`` collection: -The code examples in this guide demonstrate how you can use builders to -create types to interact with documents in the sample collection ``plants.flowers``. -Documents in this collection are modeled by the following ``Flower`` class: - -.. literalinclude:: /includes/fundamentals/code-examples/builders.cs +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs :language: csharp - :dedent: - :start-after: start-model - :end-before: end-model - -Each builder class takes a generic type parameter -``TDocument`` which represents the type of document that you are working -with. In this guide, the ``Flower`` class is the document type used in -each builder class example. - -Construct a Filter ------------------- - -The ``FilterDefinitionBuilder`` class provides a type-safe interface for -building up queries. Suppose you want to query your collection for -documents matching the following criteria: - -- ``Price`` field value less than 20 -- ``Category`` field value is "Perennial" + :start-after: start-sample-class + :end-before: end-sample-class -Use builders to create the filter definition with the typed variant: +.. _csharp-supported-vector-types: -.. code-block:: csharp - :copyable: true - - var builder = Builders.Filter; - var filter = builder.Lt(f => f.Price, 20) & builder.Eq(f => f.Category, "Perennial"); - -Using the typed variant form provides compile-time safety. Additionally, -your IDE can provide refactoring support. - -Alternatively, you can use string-based field names to contruct the filter: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Filter; - var filter = builder.Lt("Price", 20) & builder.Eq("Category", "Perennial"); - -If you are using LINQ, you can also use the ``Inject()`` method to apply the filter -to a LINQ query: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Filter; - var filter = builder.Lt("Price", 20) & builder.Eq("Category", "Perennial"); - var query = collection.AsQueryable().Where(f => filter.Inject()); - -.. _csharp-builders-array-operators: +Supported Vector Embedding Types +-------------------------------- -Array Operators -~~~~~~~~~~~~~~~ +:atlas:`Vector embeddings +` +are vectors you use to represent your data. These embeddings +capture meaningful relationships in your data and enable tasks like semantic +search and retrieval. -If your document has properties or fields that serialize to arrays, -you can use the methods beginning with ``Any``, such as ``AnyEq()`` or -``AnyLt()``, to compare the entire array against a single item. +The {+driver-short+} supports vector embeddings of several types. The following +sections describe the supported vector embedding types. -Use builders to check which documents in the collection have a -``Season`` array that includes "winter": - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Filter; - var filter = builder.AnyEq(f => f.Season, "winter"); - -You can also call the ``ElemMatch()`` method to find documents that have an -array field that contains at least one element that matches a specified search -criteria. The following example returns documents that contain the value -``"Summer"`` in their ``Season`` array: - -.. code-block:: csharp - :copyable: true +.. _csharp-vector-array-representation: - var builder = Builders.Filter; - var filter = builder.ElemMatch(f => f.Season, s => s == "Summer"); +Array Representations +~~~~~~~~~~~~~~~~~~~~~ -.. tip:: ElemMatch() Overload +The {+driver-short+} supports the following representations of the array +type in vector embeddings: - The ``ElemMatch()`` method has an overload that accepts a single *filter* - parameter. You can use this overload to perform ``$elemMatch`` - queries directly against values. This functionality can support - queries that include nested ``$elemMatch`` statements. - - The following code demonstrates how to construct a nested - ``$elemMatch`` query that uses multiple overloads of the - ``ElemMatch()`` method: - - .. code-block:: csharp - - // ElemMatch() with only filter parameter - var arrayFilter = Builders.Filter.ElemMatch(); - - // ElemMatch() with field name and filter parameters - var filter = Builders.Filter.ElemMatch(, arrayFilter); - -To learn more about array operators, see the :manual:`Array Query Operators -` guide in the {+mdb-server+} manual. - -.. _csharp-builders-projection: - -Create a Projection -------------------- - -The ``ProjectionDefinitionBuilder`` class provides a type-safe interface for -defining a projection. Suppose you want to create a projection on the -``Name`` and ``Price`` fields, but exclude the ``Id`` field. - -Use builders to create the projection definition with the typed variant: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Projection; - var projection = builder.Include(f => f.Name).Include(f => f.Price).Exclude(f => f.Id); - -You can also use string-based field names to define the projection: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Projection; - var projection = builder.Include("Name").Include("Price").Exclude("Id"); - -Finally, you can use the ``Expression()`` method to define the -projection: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Projection; - var projection = builder.Expression(f => new { Name = f.Name, Price = f.Price }); - -This definition has a return type of ``ProjectionDefinition`` whereas the others return a -``ProjectionDefinition``. - -Lambda Expressions -~~~~~~~~~~~~~~~~~~ - -The driver supports using lambda expressions to render projections. When -you define a ``Find()`` projection with the ``Expression()`` method to -create a lambda expression, the driver inspects the expression -to determine which fields are referenced and automatically constructs a -server-side projection to return only those fields. - -You can also use lambda expressions to create new fields by performing -operations on values in your documents. The following example shows how -you can use a lambda expression to project a new ``Profit`` field -using the ``Price`` and ``Stock`` fields: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Projection; - var projection = builder.Expression(f => new { Profit = f.Price * f.Stock }); - -.. note:: ``Id`` Field Exclusion - - When you create a projection using a lambda expression, the output - automatically excludes the ``Id`` field unless you explicitly include - is as a projection field. - -Define a Sort -------------- - -The ``SortDefinitionBuilder`` class provides a type-safe interface for -building up sort syntax. Suppose you want to define a sort with the -following order: - -- Ascending on ``Price`` -- Descending on ``Category`` - -Use builders to create the sort definition with the typed variant: - -.. code-block:: csharp - :copyable: true +- ``BsonArray`` +- ``Memory`` +- ``ReadOnlyMemory`` +- ``float[]`` and ``double[]`` - var builder = Builders.Sort; - var sort = builder.Ascending(f => f.Price).Descending(f => f.Category); +The following example shows a class with properties of the preceding types: -Alternatively, you can use string-based field names to define the sort: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Sort; - var sort = builder.Ascending("Price").Descending("Category"); - -Define an Update ----------------- - -The ``UpdateDefinitionBuilder`` class provides a type-safe interface for -building up an update specification. Suppose you want to create an -update specification with the following criteria: - -- Create the new field ``SunRequirement`` -- Multiply the ``Price`` field value by 0.9 - -Use builders to create the update specification with the typed variant: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Update; - var update = builder.Set(f => f.SunRequirement, "Full sun").Mul(f => f.Price, 0.9); - -Alternatively, you can use string-based field names to define the update: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.Update; - var update = builder.Set("SunRequirement", "Full sun").Mul("Price", 0.9); - -.. _csharp-builders-indexes: - -Define Index Keys ------------------ - -The ``IndexKeysDefinitionBuilder`` class provides a type-safe interface for -defining index keys. Suppose you want to select ``Category`` as an -ascending index key. - -Use builders to select the index key with the typed variant: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.IndexKeys; - var keys = builder.Ascending(f => f.Category); - -Alternatively, you can use string-based field names to select the index key: - -.. code-block:: csharp - :copyable: true - - var builder = Builders.IndexKeys; - var keys = builder.Ascending("Category"); - -The ``IndexKeysDefinitionBuilder`` class also provides methods to build -a wildcard index. You can create a wildcard index using ``All field paths`` or ``A -single field path``, in this case using ``Category``: - -.. tabs:: - - .. tab:: ``All field paths`` - :tabid: all-wildcard-index - - .. code-block:: csharp - :copyable: true - - var builder = Builders.IndexKeys; - var keys = builder.Wildcard(); - - .. tab:: ``A single field path`` - :tabid: single-wildcard-index - - .. code-block:: csharp - :copyable: true - - var builder = Builders.IndexKeys; - - // Using the typed variant - var keys = builder.Wildcard(f => f.Category); - - // Using string-based field names - var keys = builder.Wildcard("Category"); - -For more information about how to use wildcard indexes, see -:manual:`Wildcard Indexes `. - -.. _csharp-builders-aggregation: - -Build an Aggregation Pipeline ------------------------------ - -The ``PipelineDefinitionBuilder`` class provides a type-safe interface for -defining an **aggregation pipeline**. An aggregation pipeline is a series of -stages that are used to transform a document. Suppose you want to create a -pipeline that performs the following operations: - -- Matches all documents with "spring" in the ``Season`` field -- Sorts the results by the ``Category`` field -- Groups the documents by category and shows the average price and total - available for all documents in that category - -Use ``PipelineDefinitionBuilder`` classes to build the pipeline: - -.. code-block:: csharp - - var sortBuilder = Builders.Sort.Ascending(f => f.Category); - var matchFilter = Builders.Filter.AnyEq(f => f.Season, "spring"); - - var pipeline = new EmptyPipelineDefinition() - .Match(matchFilter) - .Sort(sortBuilder) - .Group(f => f.Category, - g => new - { - name = g.Key, - avgPrice = g.Average(f => f.Price), - totalAvailable = g.Sum(f => f.Stock) - } - ); - -The preceding example creates the following pipeline: - -.. code-block:: json - - [{ "$match" : { "season" : "spring" } }, { "$sort" : { "category" : 1 } }, { "$group" : { "_id" : "$category", "avgPrice" : { "$avg" : "$price" }, "totalAvailable" : { "$sum" : "$stock" } } }] - -You can add stages to your pipeline that don't have corresponding type-safe -methods in the ``PipelineDefinitionBuilder`` interface by providing your query -as a ``BsonDocument`` to the `AppendStage() method -<{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineDefinitionBuilder.AppendStage.html>`__. - -.. code-block:: csharp - - var pipeline = new EmptyPipelineDefinition().AppendStage("{ $set: { field1: '$field2' } }"); - -.. note:: - - When using a ``BsonDocument`` to define your pipeline stage, the driver does - not take into account any ``BsonClassMap``, serialization attributes or - serialization conventions. The field names used in the ``BsonDocument`` must - match those stored on the server. - - For more information on providing a query as a ``BsonDocument``, see our - :ref:`FAQ page `. +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs + :language: csharp + :start-after: start-bson-arrays + :end-before: end-bson-arrays -To learn more about the Aggregation Pipeline, see the -:manual:`Aggregation Pipeline ` server manual page. +.. tip:: -.. _csharp-builders-out: + To learn more about using the ``Memory`` and ``ReadOnlyMemory`` + types, see the :ref:`csharp-array-serialization` section of the + Serialization guide. -Write Pipeline Results to a Collection -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _csharp-binary-vector-representation: -You can write the documents returned from an aggregation pipeline to a -collection by creating an ``$out`` stage at the end of your aggregation -pipeline. To create an ``$out`` stage, call the ``Out()`` method on a -``PipelineStageDefinitionBuilder``. The ``Out()`` method requires the name of -the collection you want to write the documents to. +Binary Vector Representations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example builds an aggregation pipeline that matches all documents -with a ``season`` field value of ``"Spring"`` and outputs them to -a ``springFlowers`` collection: +The {+driver-short+} supports the following binary vector representations in +vector embeddings: -.. code-block:: csharp +- ``BinaryVectorFloat32`` (not supported on big-endian architectures) +- ``BinaryVectorInt8`` +- ``BinaryVectorPackedBit`` +- ``Memory``, ``Memory``, ``Memory`` +- ``ReadOnlyMemory``, ``ReadOnlyMemory``, ``ReadOnlyMemory`` +- ``float[]``, ``byte[]``, ``sbyte[]`` - var outputCollection = database.GetCollection("springFlowers"); - var matchFilter = Builders.Filter.AnyEq(f => f.Season, "spring"); +.. note:: - // Creates an aggregation pipeline and outputs resulting documents to a new collection. - var pipeline = new EmptyPipelineDefinition() - .Match(matchFilter) - .Out(outputCollection); + You must use the ``BinaryVector`` attribute when specifying binary vector + representations of the ``Memory``, ``ReadOnlyMemory``, or array + types. -You can write the results of an aggregation pipeline to a time series collection -by specifying a ``TimeSeriesOption`` object and passing it as the second -parameter to the ``Out()`` method. +The following example shows a class with properties of the preceding types: -Imagine that the documents in the ``plants.flowers`` collection contain a ``datePlanted`` field that -holds BSON date values. You can store the documents in this collection in a time -series collection by using the ``datePlanted`` field as the time field. - -The following example creates a ``TimeSeriesOptions`` object and specifies -``datePlanted`` as the ``timeField``. It then builds an aggregation pipeline that matches all documents -with a ``season`` field value of ``"Spring"`` and outputs them to a -time series collection called ``springFlowerTimes``. +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs + :language: csharp + :start-after: start-binary-vectors + :end-before: end-binary-vectors -.. code-block:: csharp +Binary Vector Data Serialization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - var timeSeriesOptions = new TimeSeriesOptions("datePlanted"); - var collectionName = "springFlowerTimes" - var matchFilter = Builders.Filter.AnyEq(f => f.Season, "spring"); +You can serialize ``Int8`` binary vector typed data as ``byte`` or ``sbyte``. +You can also serialize ``Float32`` binary vector typed data as ``float``. The +following example serializes ``Int8`` and ``Float32`` binary vector data: - // Creates an aggregation pipeline and outputs resulting documents to a time series collection. - var pipeline = new EmptyPipelineDefinition() - .Match(matchFilter) - .Out(collectionName, timeSeriesOptions); +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs + :language: csharp + :start-after: start-binary-int-float-serialize + :end-before: end-binary-int-float-serialize -To learn more about time series collections, see :ref:`csharp-time-series`. +You can deserialize ``PackedBit`` vector data to a :ref:`binary vector +represented ` ``byte`` data type only if the +vector data has a padding value of ``0``. If the vector data has a padding value not +equal to ``0``, you can deserialize it only to a ``BsonVectorPackedBit``. -Build an Atlas Search Query +Vector Search Query Example --------------------------- -The ``Search`` class provides a type-safe interface for creating a -:manual:`$search ` -pipeline stage. +You can perform a vector search query by calling the ``VectorSearch()`` method. +To perform a vector search on a collection, you must first have a collection with a field that contains +vector data and a vector search index that covers that field. -To learn how to construct search queries with the ``Search`` class, see -:ref:`csharp-atlas-search`. +To learn more about configuring a collection for vector search, see the :atlas:`{+avs+} +` guide in the MongoDB Atlas +documentation. -Perform an Atlas Vector Search ------------------------------- +You can convert ``BinaryVectorFloat32``, ``BinaryVectorInt8``, and +``BinaryVectorPackedBit`` data to the ``BsonBinaryData`` type to use in a vector +search query by using the ``ToQueryVector()`` method. The following example +converts ``BinaryVectorInt8`` into a ``BsonBinaryData`` object: -.. include:: /includes/vector-search-intro.rst +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs + :language: csharp + :start-after: start-to-query-vector + :end-before: end-to-query-vector - .. replacement:: mechanism +You can specify your :ref:`array-represented +` vector data as an instance of the +``QueryVector`` class to use in a vector search query. The following example +creates an array of ``ReadOnlyMemory`` values as a ``QueryVector`` object +to use in a vector search query: - builders +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs + :language: csharp + :start-after: start-array-query-vector + :end-before: end-array-query-vector + +Consider the ``embedded_movies`` collection in the ``sample_mflix`` database. You +can use a ``$vectorSearch`` stage to perform a semantic search on the ``plot_embedding`` +field of the documents in the collection. +The following sections describe different methods for performing Atlas Vector Search operations +on this collection. + +.. tip:: + + To obtain the sample dataset used in the following example, see :ref:`csharp-get-started`. + To create the sample Atlas Vector Search index used in the following example, see + :atlas:`Create an Atlas Vector Search Index ` in the + Atlas manual. + +Aggregation Pipeline Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example performs the following steps to run an {+avs+} query on a collection that +contains vector data and a vector search index on the ``PlotEmbedding`` field: + +1. Creates an array that contains the :ref:`array-represented + ` vector data to search for +#. Specifies a ``VectorSearchOptions`` object that contains the name of the index + and the number of nearest neighbors to use during the search +#. Creates an aggregation pipeline that uses the ``VectorSearch()`` stage to + perform the vector search query and a ``Project()`` stage to display only + the ``Title``, ``Plot``, and ``Score`` fields +#. Prints the results of the query .. code-block:: csharp @@ -472,46 +214,61 @@ Perform an Atlas Vector Search // Builds aggregation pipeline and specifies that the $vectorSearch stage // returns 10 results var pipeline = new EmptyPipelineDefinition() - .VectorSearch(m => m.Embedding, vector, 10, options) + .VectorSearch(m => m.PlotEmbedding, vector, 10, options) .Project(Builders.Projection .Include(m => m.Title) - .Include(m => m.Plot)); + .Include(m => m.Plot) + .MetaVectorSearchScore(m => m.Score); The results of the preceding example contain the following documents: .. code-block:: json - { "_id" : ObjectId("573a13a0f29313caabd04a4f"), "plot" : "A reporter, learning of time travelers visiting 20th century disasters, tries to change the history they know by averting upcoming disasters.", "title" : "Thrill Seekers" } - { "_id" : ObjectId("573a13d8f29313caabda6557"), "plot" : "At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.", "title" : "About Time" } - { "_id" : ObjectId("573a13a5f29313caabd13b4b"), "plot" : "Hoping to alter the events of the past, a 19th century inventor instead travels 800,000 years into the future, where he finds humankind divided into two warring races.", "title" : "The Time Machine" } - { "_id" : ObjectId("573a13aef29313caabd2e2d7"), "plot" : "After using his mother's newly built time machine, Dolf gets stuck involuntary in the year 1212. He ends up in a children's crusade where he confronts his new friends with modern techniques...", "title" : "Crusade in Jeans" } - { "_id" : ObjectId("573a1399f29313caabceec0e"), "plot" : "An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.", "title" : "Timecop" } - { "_id" : ObjectId("573a1399f29313caabcee36f"), "plot" : "A time-travel experiment in which a robot probe is sent from the year 2073 to the year 1973 goes terribly wrong thrusting one of the project scientists, a man named Nicholas Sinclair into a...", "title" : "A.P.E.X." } - { "_id" : ObjectId("573a13c6f29313caabd715d3"), "plot" : "Agent J travels in time to M.I.B.'s early days in 1969 to stop an alien from assassinating his friend Agent K and changing history.", "title" : "Men in Black 3" } - { "_id" : ObjectId("573a13d4f29313caabd98c13"), "plot" : "Bound by a shared destiny, a teen bursting with scientific curiosity and a former boy-genius inventor embark on a mission to unearth the secrets of a place somewhere in time and space that exists in their collective memory.", "title" : "Tomorrowland" } - { "_id" : ObjectId("573a13b6f29313caabd477fa"), "plot" : "With the help of his uncle, a man travels to the future to try and bring his girlfriend back to life.", "title" : "Love Story 2050" } - { "_id" : ObjectId("573a13e5f29313caabdc40c9"), "plot" : "A dimension-traveling wizard gets stuck in the 21st century because cell-phone radiation interferes with his magic. With his home world on the brink of war, he seeks help from a jaded ...", "title" : "The Portal" } - -To learn more about Atlas Vector Search, see -:atlas:`Atlas Vector Search Overview ` -in the Atlas manual. + { "_id" : { "$oid" : "573a13a0f29313caabd04a4f" }, "plot" : "A reporter, learning of time travelers visiting 20th century disasters, tries to change the history they know by averting upcoming disasters.", "title" : "Thrill Seekers", "score" : 0.926971435546875 } + { "_id" : { "$oid" : "573a13d8f29313caabda6557" }, "plot" : "At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.", "title" : "About Time", "score" : 0. 9267120361328125 } + { "_id" : { "$oid" : "573a1399f29313caabceec0e" }, "plot" : "An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.", "title" : "Timecop", "score" : 0.9235687255859375 } + { "_id" : { "$oid" : "573a13a5f29313caabd13b4b" }, "plot" : "Hoping to alter the events of the past, a 19th century inventor instead travels 800,000 years into the future, where he finds humankind divided into two warring races.", "title" : "The Time Machine", "score" : 0.9228668212890625 } + { "_id" : { "$oid" : "573a13aef29313caabd2e2d7" }, "plot" : "After using his mother's newly built time machine, Dolf gets stuck involuntary in the year 1212. He ends up in a children's crusade where he confronts his new friends with modern techniques...", "title" : "Crusade in Jeans", "score" : 0.9228515625 } + { "_id" : { "$oid" : "573a1399f29313caabcee36f" }, "plot" : "A time-travel experiment in which a robot probe is sent from the year 2073 to the year 1973 goes terribly wrong thrusting one of the project scientists, a man named Nicholas Sinclair into a...", "title" : "A.P.E.X.", "score" : 0.9199066162109375 } + { "_id" : { "$oid" : "573a13c6f29313caabd715d3" }, "plot" : "Agent J travels in time to M.I.B.'s early days in 1969 to stop an alien from assassinating his friend Agent K and changing history.", "title" : "Men in Black 3", "score" : 0.919403076171875 } + { "_id" : { "$oid" : "573a13d4f29313caabd98c13" }, "plot" : "Bound by a shared destiny, a teen bursting with scientific curiosity and a former boy-genius inventor embark on a mission to unearth the secrets of a place somewhere in time and space that exists in their collective memory.", "title" : "Tomorrowland", "score" : 0.9191131591796875 } + { "_id" : { "$oid" : "573a13b6f29313caabd477fa" }, "plot" : "With the help of his uncle, a man travels to the future to try and bring his girlfriend back to life.", "title" : "Love Story 2050", "score" : 0. 917755126953125 } + { "_id" : { "$oid" : "573a13b3f29313caabd3ebd4" }, "plot" : "A romantic drama about a Chicago librarian with a gene that causes him to involuntarily time travel, and the complications it creates for his marriage.", "title" : "The Time Traveler's Wife", "score" : 0.9172210693359375 } + +LINQ Example +~~~~~~~~~~~~ + +The following code sample performs the same vector search query as the preceding example, but uses +the LINQ syntax instead of the aggregation pipeline syntax: + +.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs + :language: csharp + :start-after: start-linq-example + :end-before: end-linq-example + :dedent: + :emphasize-lines: 2 Additional Information ---------------------- -Find runnable examples using builders for various operations under -:ref:`Usage Examples `. +To learn more about {+avs+}, see the :atlas:`{+avs+} +` guide in the MongoDB Atlas +documentation. API Documentation ~~~~~~~~~~~~~~~~~ -To learn more about any of the methods or types discussed in this +To learn more about any of the functions or types discussed in this guide, see the following API Documentation: -- `FilterDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinitionBuilder-1.html>`__ -- `ProjectionDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.html>`__ -- `SortDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SortDefinitionBuilder-1.html>`__ -- `UpdateDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinitionBuilder-1.html>`__ -- `IndexKeysDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IndexKeysDefinitionBuilder-1.html>`__ -- `PipelineDefinitionBuilder - <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineDefinitionBuilder.html>`__ +- `BinaryVectorFloat32 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorFloat32.html>`__ +- `BinaryVectorInt8 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorInt8.html>`__ +- `BinaryVectorPackedBit <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorPackedBit.html>`__ +- `QueryVector <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.QueryVector.html>`__ +- `ToQueryVector() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BinaryVectorDriverExtensions.ToQueryVector.html>`__ +- `IAggregateFluentExtensions.VectorSearch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAggregateFluentExtensions.VectorSearch.html>`__ +- `Aggregate() + <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Aggregate.html>`__ +- `MongoQueryable.VectorSearch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.VectorSearch.html>`__ +- `PipelineStageDefinitionBuilder.VectorSearch() + <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineStageDefinitionBuilder.VectorSearch.html>`__ diff --git a/source/connect.txt b/source/connect.txt new file mode 100644 index 00000000..6d3ed20d --- /dev/null +++ b/source/connect.txt @@ -0,0 +1,28 @@ +.. _csharp-connect: + +================== +Connect to MongoDB +================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Connect to a MongoDB instance or replica set using the .NET/C# Driver by configuring a connection URI or `MongoClientSettings` for various deployment types. + :keywords: client, ssl + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Create a MongoClient + Choose a Connection Target + Specify Connection Options + Connection Troubleshooting \ No newline at end of file diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt new file mode 100644 index 00000000..2eedf30e --- /dev/null +++ b/source/connect/connection-options.txt @@ -0,0 +1,1370 @@ +.. _csharp-connection-options: + +========================== +Specify Connection Options +========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, Atlas, settings, configure + :description: Explore MongoDB connection and authentication options in the .NET/C# Driver using connection URI or `MongoClientSettings` for flexible configuration. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. toctree:: + :caption: Specify Connection Options + + Compress Network Traffic + Customize Server Selection + Stable API + Connection Pools + Connect from AWS Lambda + +Overview +-------- + +This page describes the connection options available in the {+driver-short+} and +explains how to apply them to your MongoDB connection. + +How to Specify Connection Options +--------------------------------- + +The following sections describe the ways in which you can specify connection options. + +.. _csharp-connection-uri: + +Using the Connection URI +~~~~~~~~~~~~~~~~~~~~~~~~ + +If you pass a connection URI to the ``MongoClient`` constructor, you can include +connection options in the string as ``=`` pairs. In the following example, +the connection URI contains the ``connectTimeoutMS`` option with a value of ``60000`` +and the ``tls`` option with a value of ``true``: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :dedent: + :start-after: // start-connection-uri + :end-before: // end-connection-uri + +To learn more about the options that you can specify in a connection URI, see +:manual:`Connection String Options ` in the +{+mdb-server+} manual. + +.. _csharp-mongo-client-settings: + +Using MongoClientSettings +~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use a ``MongoClientSettings`` object to configure connection settings in code +rather than in a connection URI. Configuring the connection this way makes it easier to +change settings at runtime, helps you catch errors during compilation, and provides +more configuration options than the connection URI. + +To set connection options in a ``MongoClientSettings`` object, perform the +following steps: + +1. Create an instance of the ``MongoClientSettings`` class +#. Set properties on the instance to configure the connection +#. Pass the instance to the ``MongoClient`` constructor + +The following code example shows how to perform the preceding steps: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :dedent: + :start-after: // start-mongo-client-settings + :end-before: // end-mongo-client-settings + +You can also create a ``MongoClientSettings`` object from a connection string by calling the +``MongoClientSettings.FromConnectionString()`` method and passing the connection string, +as shown in the following example. This is useful if you already have a connection string +but want to modify some settings programmatically, or if you must specify settings +that aren't available in the connection string. + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :dedent: + :start-after: // start-from-connection-string + :end-before: // end-from-connection-string + +Alternatively, you can create a ``MongoClientSettings`` object from a ``MongoUrl`` object +by calling the ``MongoClientSettings.FromUrl()`` method and passing the ``MongoUrl`` +object, as shown in the following example. This is useful if you already have a ``MongoUrl`` +object but want to specify settings that aren't available in the ``MongoUrl`` class. + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :dedent: + :start-after: // start-from-url + :end-before: // end-from-url + +.. _csharp-mongo-url-builder: + +Using MongoUrlBuilder +~~~~~~~~~~~~~~~~~~~~~ + +You can use a ``MongoUrlBuilder`` object to create and configure connection settings on +a ``MongoUrl`` object. A ``MongoUrl`` is a strongly typed representation of a +connection URI, and is useful when reading a connection URI directly from +another source. Using a ``MongoUrl`` object has many of the same advantages as using +a ``MongoClientSettings`` object, although the two classes contain different properties +and methods. + +To use a ``MongoUrlBuilder`` object, create an instance of the class and set the +necessary configuration properties. To create a ``MongoUrl`` object from the +``MongoUrlBuilder``, call the ``MongoUrlBuilder.ToMongoUrl()`` method. You can pass the +``MongoUrl`` object to the ``MongoClient`` constructor. The following code example shows +this process: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :dedent: 8 + :start-after: // start-mongo-url-builder + :end-before: // end-mongo-url-builder + +Connection Options +------------------ + +The following sections describe the connection options available in the +{+driver-short+} and how to specify them by using a ``MongoClientSettings`` or +``MongoUrlBuilder`` object. + +.. _csharp-replica-set-options: + +Replica Set Options +~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + DirectConnection + ```````````````` + + .. include:: /includes/fundamentals/connection-options/directConnection.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-direct-connection + :end-before: // end-settings-direct-connection + + ReplicaSetName + `````````````` + + .. include:: /includes/fundamentals/connection-options/replicaSetName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-replica-set-name + :end-before: // end-settings-replica-set-name + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + DirectConnection + ```````````````` + + .. include:: /includes/fundamentals/connection-options/directConnection.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-direct-connection + :end-before: // end-builder-direct-connection + + ReplicaSetName + `````````````` + + .. include:: /includes/fundamentals/connection-options/replicaSetName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-replica-set-name + :end-before: // end-builder-replica-set-name + +TLS Options +~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + AllowInsecureTls + ```````````````` + + .. include:: /includes/fundamentals/connection-options/allowInsecureTls.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-allow-insecure-tls + :end-before: // end-settings-allow-insecure-tls + + SslSettings + ``````````` + + TLS/SSL options, including client certificates, revocation handling, and + enabled and disabled TLS/SSL protocols. The default value is ``null``. + + If ``SslSettings.CheckCertificateRevocation`` is set to ``false`` and + ``AllowInsecureTls`` is set to ``true``, the {+driver-short+} throws + an exception. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-ssl-settings + :end-before: // end-settings-ssl-settings + + UseTls + `````` + + .. include:: /includes/fundamentals/connection-options/useTls.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-use-tls + :end-before: // end-settings-use-tls + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + AllowInsecureTls + ```````````````` + + .. include:: /includes/fundamentals/connection-options/allowInsecureTls.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-allow-insecure-tls + :end-before: // end-builder-allow-insecure-tls + + TlsDisableCertificateRevocationCheck + ```````````````````````````````````` + + Whether to disable certificate revocation checking during the TLS handshake. The + default value is ``false``. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-tls-disable + :end-before: // end-builder-tls-disable + + UseTls + `````` + + .. include:: /includes/fundamentals/connection-options/useTls.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-use-tls + :end-before: // end-builder-use-tls + +Timeout Options +~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + ConnectTimeout + `````````````` + + .. include:: /includes/fundamentals/connection-options/connectTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-connect-timeout + :end-before: // end-settings-connect-timeout + + SocketTimeout + ````````````` + + .. include:: /includes/fundamentals/connection-options/socketTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-connect-timeout + :end-before: // end-settings-connect-timeout + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + ConnectTimeout + `````````````` + + .. include:: /includes/fundamentals/connection-options/connectTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-connect-timeout + :end-before: // end-builder-connect-timeout + + SocketTimeout + ````````````` + + .. include:: /includes/fundamentals/connection-options/socketTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-socket-timeout + :end-before: // end-builder-socket-timeout + +Compression Options +~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + Compressors + ``````````` + + .. include:: /includes/fundamentals/connection-options/compressors.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-compressors + :end-before: // end-settings-compressors + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + Compressors + ``````````` + + .. include:: /includes/fundamentals/connection-options/compressors.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-compressors + :end-before: // end-builder-compressors + +Connection Pool Options +~~~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + MaxConnecting + ````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnecting.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-max-connecting + :end-before: // end-settings-max-connecting + + MaxConnectionIdleTime + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionIdleTime.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-max-connection-idle-time + :end-before: // end-settings-max-connection-idle-time + + MaxConnectionLifeTime + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionLifetime.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-max-connection-life-time + :end-before: // end-settings-max-connection-life-time + + MaxConnectionPoolSize + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionPoolSize.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-max-connection-pool-size + :end-before: // end-settings-max-connection-pool-size + + MinConnectionPoolSize + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/minConnectionPoolSize.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-min-connection-pool-size + :end-before: // end-settings-min-connection-pool-size + + WaitQueueTimeout + ```````````````` + + .. include:: /includes/fundamentals/connection-options/waitQueueTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-wait-queue-timeout + :end-before: // end-settings-wait-queue-timeout + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + MaxConnecting + ````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnecting.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-max-connecting + :end-before: // end-builder-max-connecting + + MaxConnectionIdleTime + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionIdleTime.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-max-connection-idle-time + :end-before: // end-builder-max-connection-idle-time + + MaxConnectionLifeTime + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionLifetime.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-max-connection-life-time + :end-before: // end-builder-max-connection-life-time + + MaxConnectionPoolSize + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/maxConnectionPoolSize.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-max-connection-pool-size + :end-before: // end-builder-max-connection-pool-size + + MinConnectionPoolSize + ````````````````````` + + .. include:: /includes/fundamentals/connection-options/minConnectionPoolSize.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-min-connection-pool-size + :end-before: // end-builder-min-connection-pool-size + + WaitQueueTimeout + ```````````````` + + .. include:: /includes/fundamentals/connection-options/waitQueueTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-wait-queue-timeout + :end-before: // end-builder-wait-queue-timeout + +Write Concern Options +~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + WriteConcern + ```````````` + + The default write-concern settings, including write timeout and + journaling, for the client. The default value is ``WriteConcern.Acknowledged``. + See :manual:`Write Concern ` in the + {+mdb-server+} manual for more information. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-write-concern + :end-before: // end-settings-write-concern + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + FSync + ````` + + The FSync component of the write concern. The default value is ``false``. To learn + more about the ``fsync`` command, see :manual:`fsync ` + in the {+mdb-server+} manual. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-fsync + :end-before: // end-builder-fsync + + Journal + ``````` + + The ``j`` component of the write concern, which requests acknowledgment that the + MongoDB instances have written to the on-disk journal. The default value depends on + the value in the ``writeConcernMajorityJournalDefault`` setting. To learn more about the + ``j`` option, see :manual:`Write Concern ` + in the {+mdb-server+} manual. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-journal + :end-before: // end-builder-journal + + W + `` + + The ``w`` component of the write concern, which requests acknowledgment that the write + operation has propagated to a specified number of MongoDB instances. The default + value is ``"majority"`` or ``1``, depending on the number of arbiters and voting nodes. + To learn more about the ``w`` option, see :manual:`Write Concern ` + in the {+mdb-server+} manual. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-w + :end-before: // end-builder-w + + WTimeout + ```````` + + The ``wtimeout`` component of the write concern, which specifies a time limit for the + write concern. To learn more about the ``wtimeout`` option, see + :manual:`Write Concern ` + in the {+mdb-server+} manual. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-w-timeout + :end-before: // end-builder-w-timeout + +Read Concern Options +~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + ReadConcern + ``````````` + + The client's read concern. The default value is ``ReadConcern.Default``. + For more information, see :manual:`Read Concern ` in the + {+mdb-server+} manual. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-read-concern + :end-before: // end-settings-read-concern + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + ReadConcernLevel + ```````````````` + + The client's read concern level. The default value is ``ReadConcern.Local``. + For more information, see :ref:`read concern `. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-read-concern-level + :end-before: // end-builder-read-concern-level + +Read Preference Options +~~~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + ReadPreference + `````````````` + + .. include:: /includes/fundamentals/connection-options/readPreference.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-read-preference + :end-before: // end-settings-read-preference + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + .. include:: /includes/fundamentals/connection-options/readPreference.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-read-preference + :end-before: // end-builder-read-preference + +Authentication Options +~~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + Credential + `````````` + + Settings for how the driver authenticates to the server. This includes + authentication credentials, mechanism, source, and other settings. The default + value is ``null``. + + If you don't specify an authentication mechanism, the driver uses either + ``SCRAM-SHA-1`` or ``SCRAM-SHA-256``, depending on the server version. See + :ref:`Authentication Mechanisms ` for available + authentication mechanisms. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-credential + :end-before: // end-settings-credential + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + AuthenticationMechanism + ``````````````````````` + + The mechanism that the driver uses to authenticate to {+mdb-server+}. + If you don't specify an authentication mechanism, the driver uses either + ``SCRAM-SHA-1`` or ``SCRAM-SHA-256``, depending on the server version. See + :ref:`authentication mechanisms ` for available + authentication mechanisms. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-authentication + :end-before: // end-builder-authentication + :emphasize-lines: 3 + + AuthenticationMechanismProperties + ````````````````````````````````` + + Configuration settings for the authentication mechanism specified in the + ``AuthenticationMechanism`` property. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-authentication + :end-before: // end-builder-authentication + :emphasize-lines: 4-8 + + AuthenticationSource + ```````````````````` + + The source to authenticate the client against. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-authentication + :end-before: // end-builder-authentication + :emphasize-lines: 9 + + Password + ```````` + + The password to use for authentication. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-username-password + :end-before: // end-builder-username-password + :emphasize-lines: 4 + + Username + ```````` + + The username to use for authentication. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-username-password + :end-before: // end-builder-username-password + :emphasize-lines: 3 + +Server Selection and Discovery Options +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + HeartbeatInterval + ````````````````` + + .. include:: /includes/fundamentals/connection-options/heartbeatInterval.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-heartbeat-interval + :end-before: // end-settings-heartbeat-interval + + HeartbeatTimeout + ```````````````` + + .. include:: /includes/fundamentals/connection-options/heartbeatTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-heartbeat-timeout + :end-before: // end-settings-heartbeat-timeout + + LocalThreshold + `````````````` + + .. include:: /includes/fundamentals/connection-options/localThreshold.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-local-threshold + :end-before: // end-settings-local-threshold + + ServerSelectionTimeout + `````````````````````` + + .. include:: /includes/fundamentals/connection-options/localThreshold.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-server-selection-timeout + :end-before: // end-settings-server-selection-timeout + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + HeartbeatInterval + ````````````````` + + .. include:: /includes/fundamentals/connection-options/heartbeatInterval.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-heartbeat-interval + :end-before: // end-builder-heartbeat-interval + + HeartbeatTimeout + ```````````````` + + .. include:: /includes/fundamentals/connection-options/heartbeatTimeout.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-heartbeat-timeout + :end-before: // end-builder-heartbeat-timeout + + LocalThreshold + `````````````` + + .. include:: /includes/fundamentals/connection-options/localThreshold.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-local-threshold + :end-before: // end-builder-local-threshold + + ServerSelectionTimeout + `````````````````````` + + .. include:: /includes/fundamentals/connection-options/localThreshold.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-server-selection-timeout + :end-before: // end-builder-server-selection-timeout + +Encoding Options +~~~~~~~~~~~~~~~~ + +ReadEncoding +```````````` + +The UTF-8 encoding to use for string deserialization. The default value is +strict encoding, where the driver throws an exception when it encounters an invalid +UTF-8 byte sequence + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-read-encoding + :end-before: // end-settings-read-encoding + +WriteEncoding +````````````` + +The UTF-8 encoding to use for string serialization. The default value is +strict encoding, where the driver throws an exception when it encounters an invalid +UTF-8 byte sequence + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-write-encoding + :end-before: // end-settings-write-encoding + +.. note:: MongoClientSettings Only + + The ``ReadEncoding`` and ``WriteEncoding`` properties are available only in the + ``MongoClientSettings`` class. + +Stable API +~~~~~~~~~~ + +ServerApi +````````` + +Allows opting into Stable API versioning. The default value is ``null``. See +:manual:`Stable API ` in the {+mdb-server+} manual for more +information about Stable API versioning. + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-server-api + :end-before: // end-settings-server-api + +.. note:: MongoClientSettings Only + + The ``ServerApi`` property is available only in the ``MongoClientSettings`` class. + +Retry Options +~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + RetryReads + `````````` + + .. include:: /includes/fundamentals/connection-options/retryReads.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-retry-reads + :end-before: // end-settings-retry-reads + + RetryWrites + ``````````` + + .. include:: /includes/fundamentals/connection-options/retryWrites.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-retry-writes + :end-before: // end-settings-retry-writes + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + RetryReads + `````````` + + .. include:: /includes/fundamentals/connection-options/retryReads.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-retry-reads + :end-before: // end-builder-retry-reads + + RetryWrites + ``````````` + + .. include:: /includes/fundamentals/connection-options/retryWrites.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-retry-writes + :end-before: // end-builder-retry-writes + +Miscellaneous Options +~~~~~~~~~~~~~~~~~~~~~ + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongo-client-settings + + ApplicationName + ``````````````` + + .. include:: /includes/fundamentals/connection-options/applicationName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-application-name + :end-before: // end-settings-application-name + + AutoEncryptionOptions + ````````````````````` + + Settings for automatic client-side encryption. The default value is ``null``. To + learn more about client-side encryption, see + :ref:`In-Use Encryption `. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-auto-encryption-options + :end-before: // end-settings-auto-encryption-options + + ClusterConfigurator + ``````````````````` + + Low-level configuration options for sockets, TLS, cluster, and others. The default + value is ``null``. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-cluster-configurator + :end-before: // end-settings-cluster-configurator + + IPv6 + ```` + + .. include:: /includes/fundamentals/connection-options/ipv6.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-ipv6 + :end-before: // end-settings-ipv6 + + IsFrozen + ```````` + + A read-only option that indicates whether the settings have been frozen. You can't + change frozen settings. The default value is ``false``. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-is-frozen + :end-before: // end-settings-is-frozen + + .. tip:: Freeze Settings + + You can freeze the settings on a ``MongoClientSettings`` object by calling its + `Freeze() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.Freeze.html>`__ + method. This prevents any further changes to the settings. + + Alternatively, you can call the `FrozenCopy() + <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.FrozenCopy.html>`__ + method to create a new ``MongoClientSettings`` object with the current settings frozen. + + LibraryInfo + ``````````` + + The name and version of a custom library built on the {+driver-short+}. The driver + sends this information to the server. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-library-info + :end-before: // end-settings-library-info + + LoadBalanced + ```````````` + + .. include:: /includes/fundamentals/connection-options/loadBalanced.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-load-balanced + :end-before: // end-settings-load-balanced + + LoggingSettings + ``````````````` + + The settings used for :ref:`logging. ` The default value is ``null``. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-logging-settings + :end-before: // end-settings-logging-settings + + Scheme + `````` + + .. include:: /includes/fundamentals/connection-options/scheme.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-scheme + :end-before: // end-settings-scheme + + Server + `````` + + .. include:: /includes/fundamentals/connection-options/server.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-server + :end-before: // end-settings-server + + ServerMonitoringMode + ```````````````````` + + .. include:: /includes/fundamentals/connection-options/serverMonitoringMode.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-server-monitoring-mode + :end-before: // end-settings-server-monitoring-mode + + Servers + ``````` + + .. include:: /includes/fundamentals/connection-options/servers.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-servers + :end-before: // end-settings-servers + + SrvMaxHosts + ``````````` + + .. include:: /includes/fundamentals/connection-options/srvMaxHosts.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-srv-max-hosts + :end-before: // end-settings-srv-max-hosts + + SrvServiceName + `````````````` + + .. include:: /includes/fundamentals/connection-options/srvServiceName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-srv-service-name + :end-before: // end-settings-srv-service-name + + TranslationOptions + `````````````````` + + Specifies options, such as the {+mdb-server+} version, for translating LINQ + queries to the Query API. The default value is ``null``. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-settings-translation-options + :end-before: // end-settings-translation-options + + .. tab:: MongoUrlBuilder + :tabid: mongo-url-builder + + ApplicationName + ``````````````` + + .. include:: /includes/fundamentals/connection-options/applicationName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-application-name + :end-before: // end-builder-application-name + + DatabaseName + ```````````` + + The name of the database that the client connects to. + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-database-name + :end-before: // end-builder-database-name + + IPv6 + ```` + + .. include:: /includes/fundamentals/connection-options/ipv6.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-ipv6 + :end-before: // end-builder-ipv6 + + LoadBalanced + ```````````` + + .. include:: /includes/fundamentals/connection-options/loadBalanced.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-load-balanced + :end-before: // end-builder-load-balanced + + Scheme + `````` + + .. include:: /includes/fundamentals/connection-options/scheme.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-scheme + :end-before: // end-builder-scheme + + Server + `````` + + .. include:: /includes/fundamentals/connection-options/server.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-server + :end-before: // end-builder-server + + ServerMonitoringMode + ```````````````````` + + .. include:: /includes/fundamentals/connection-options/serverMonitoringMode.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-server-monitoring-mode + :end-before: // end-builder-server-monitoring-mode + + Servers + ``````` + + .. include:: /includes/fundamentals/connection-options/servers.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-servers + :end-before: // end-builder-servers + + SrvMaxHosts + ``````````` + + .. include:: /includes/fundamentals/connection-options/srvMaxHosts.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-srv-max-hosts + :end-before: // end-builder-srv-max-hosts + + SrvServiceName + `````````````` + + .. include:: /includes/fundamentals/connection-options/srvServiceName.rst + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ConnectionOptions.cs + :language: csharp + :copyable: true + :dedent: 8 + :start-after: // start-builder-srv-service-name + :end-before: // end-builder-srv-service-name + +Additional Information +---------------------- + +For more information about the types used on this page, see the +following API documentation: + +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `MongoUrl <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoUrl.html>`__ +- `MongoUrlBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoUrlBuilder.html>`__ +- `AutoEncryptionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AutoEncryptionOptions.html>`__ +- `ClusterDescriptionChangedEvent <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Events.ClusterDescriptionChangedEvent.html>`__ +- `ClusterOpenedEvent <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Events.ClusterOpenedEvent.html>`__ +- `CollectionNamespace <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html>`__ +- `CompressorConfiguration <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.CompressorConfiguration.html>`__ +- `CompressorType <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Compression.CompressorType.html>`__ +- `ConnectionStringScheme <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ConnectionStringScheme.html>`__ +- `ExpressionTranslationOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ExpressionTranslationOptions.html>`__ +- `LoggingSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.LoggingSettings.html>`__ +- `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Credential.html>`__ +- `MongoServerAddress <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoServerAddress.html>`__ +- `ReadConcern <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadConcern.html>`__ +- `ReadConcernLevel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadConcernLevel.html>`__ +- `ReadPreference <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadPreference.html>`__ +- `ServerApi <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ServerApi.html>`__ +- `WriteConcern <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.WriteConcern.html>`__ \ No newline at end of file diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt new file mode 100644 index 00000000..e2d7d3d0 --- /dev/null +++ b/source/connect/connection-options/connection-pools.txt @@ -0,0 +1,151 @@ +.. _csharp-faq-connection-pool: +.. _csharp-connection-pools: + +================ +Connection Pools +================ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection, client, latency + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn about how the {+driver-short+} uses connection pools to manage +connections to a MongoDB deployment and how you can configure connection pool settings +in your application. + +A connection pool is a cache of open database connections maintained by the {+driver-short+}. +When your application requests a connection to MongoDB, the {+driver-short+} seamlessly +gets a connection from the pool, performs operations, and returns the connection +to the pool for reuse. + +Connection pools help reduce application latency and the number of times new connections +are created by the {+driver-short+}. The following diagram illustrates a high-level view +of how the ``MongoClient`` manages a connection pool: + +.. figure:: /includes/figures/CMAP_diagram.svg + :alt: CMAP diagram + +Configuring Connection Pools +---------------------------- + +You can specify the following connection pool settings in your ``MongoClient`` object or in +your connection URI: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Setting + - Description + + * - ``ConnectTimeout`` + - | The maximum amount of time that the {+driver-short+} waits when establishing a new + connection before timing out. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 30 seconds + | **Connection URI Example**: ``connectTimeoutMS=0`` + + * - ``MaxConnecting`` + - | The maximum number of connections that each pool can establish concurrently. + If this limit is reached, further requests wait until a connection is established + or another in-use connection is checked back into the pool. + | + | **Data Type**: ``integer`` + | **Default**: ``2`` + | **Connection URI Example**: ``maxConnecting=3`` + + * - ``MaxConnectionIdleTime`` + - | The maximum time that a connection can remain idle in the pool. When a connection + exceeds this limit, the {+driver-short+} closes the connection and removes it from + the pool. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 10 minutes + | **Connection URI Example**: ``maxIdleTimeMS=60000`` + + * - ``MaxConnectionLifeTime`` + - | The maximum time that a connection can be pooled. When a connection exceeds this + limit, the {+driver-short+} closes the connection and removes it from the pool. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 30 minutes + | **Connection URI Example**: ``maxLifeTimeMS=50000`` + + * - ``MaxConnectionPoolSize`` + - | The maximum number of concurrent connections that the pool maintains. + If the maximum pool size is reached, further requests wait until a connection + becomes available. + | + | **Data Type**: ``integer`` + | **Default**: ``100`` + | **Connection URI Example**: ``maxPoolSize=150`` + + * - ``MinConnectionPoolSize`` + - | The minimum number of concurrent connections that the pool maintains. If + the number of open connections falls below this value due to network errors, + the {+driver-short+} attempts to create new connections to maintain this minimum. + | + | **Data Type**: ``integer`` + | **Default**: ``0`` + | **Connection URI Example**: ``minPoolSize=3`` + + * - ``SocketTimeout`` + - | The length of time that the {+driver-short+} waits for a response from the server + before timing out. + | + | **Data Type**: ``TimeSpan`` + | **Default**: OS default + | **Connection URI Example**: ``socketTimeoutMS=100000`` + + * - ``WaitQueueTimeout`` + - | How long a thread waits for a connection to become available in the connection pool + before timing out. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 2 minutes + | **Connection URI Example**: ``waitQueueTimeoutMS=100000`` + +The following code creates a client with a maximum connection pool size of ``50`` by using the +``MaxConnectionPoolSize`` parameter: + +.. code-block:: csharp + + var settings = MongoClientSettings.FromConnectionString(""); + settings.MaxConnectionPoolSize = 50; + var client = new MongoClient(settings); + +The following code creates a client with the same configuration as the preceding example, +but uses a connection URI: + +.. code-block:: csharp + + var settings = MongoClientSettings.FromConnectionString("?maxPoolSize=50"); + var client = new MongoClient(settings); + +Additional Information +---------------------- + +To learn more about connection pools, see :manual:`Connection Pool Overview ` +in the {+mdb-server+} manual. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ diff --git a/source/fundamentals/connection/network-compression.txt b/source/connect/connection-options/network-compression.txt similarity index 100% rename from source/fundamentals/connection/network-compression.txt rename to source/connect/connection-options/network-compression.txt diff --git a/source/connect/connection-options/server-selection.txt b/source/connect/connection-options/server-selection.txt new file mode 100644 index 00000000..fc750f3d --- /dev/null +++ b/source/connect/connection-options/server-selection.txt @@ -0,0 +1,195 @@ +.. _csharp-server-selection: + +========================== +Customize Server Selection +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, read preference, write + +Overview +-------- + +All MongoDB drivers follow a defined algorithm when selecting a server to read or write +from. By using the ``ClusterConfigurator`` property of a ``MongoClient`` object, you can +customize this algorithm to choose the server that works best for your application. + +.. important:: + + Customizing the server selection algorithm might have unintended consequences, + such as degraded read or write performance. + +Default Algorithm +----------------- + +When the {+driver-short+} executes a read operation, it performs the following steps, +in order, to select a MongoDB deployment: + +1. Selects all servers that match the active read preference from the list of known servers. + +#. If at least one readable server exists, the driver calls the user-defined + server-selector function and passes in the list from the previous step. + +#. Applies the ``LocalThreshold`` connection setting to the list of + servers returned from the function. + +#. Selects a server at random from the servers still on the list and + executes the operation against this server. + +When the {+driver-short+} executes a write operation, it begins by selecting all writeable +servers, not just those that match the active read preference. The remaining steps are +identical. + +To learn more about the default server selection algorithm, which the driver follows +when you don't specify any custom server selection logic, see +:manual:`Server Selection Algorithm ` in the +{+mdb-server+} manual. + +.. _csharp-server-selection-algorithm: + +Specifying Other Server Selection Algorithms +-------------------------------------------- + +You can specify different server selection logic by passing an instance of a server selector +class to the ``PreServerSelector`` or ``PostServerSelector`` property of the ``ClusterConfigurator``. The +``PreServerSelector`` property specifies a server selector that runs before the +standard server selection logic runs, while the ``PostServerSelector`` property +specifies a server selector that runs after standard server selection logic runs. You can +then pass your ``ClusterConfigurator`` instance to the ``MongoClientSettings`` object when you create a +``MongoClient`` instance to apply your custom server selection logic. + +The following table lists the different types of server selectors you can pass to the +``ClusterConfigurator`` property: + +.. list-table:: + :header-rows: 1 + :widths: 40 60 + + * - Server Selector + - Description + + * - ``CompositeServerSelector`` + - Selects servers based on multiple partial selectors + + * - ``DelegateServerSelector`` + - Wraps a delegate server selector + + * - ``EndPointServerSelector`` + - Selects servers based on their endpoint + + * - ``LatencyLimitingServerSelector`` + - Selects servers within an acceptable latency range + + * - ``PriorityServerSelector`` + - Selects a server based on a collection of servers to deprioritize + + * - ``RandomServerSelector`` + - Selects a random server + + * - ``ReadPreferenceServerSelector`` + - Selects servers based on a specified read preference + +The following example instructs a ``MongoClient`` to use the ``RandomServerSelector`` +class to select a server at random before the standard server selection logic runs: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ServerSelection.cs + :start-after: start-server-selector + :end-before: end-server-selector + :language: csharp + :dedent: + +To learn more about the different server selector classes, see the +`ServerSelectors API documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.html>`__. + +Implementing Custom Server Selection Logic +------------------------------------------ + +You can implement your own custom server selection logic by creating a class that +inherits from the ``IServerSelector`` interface and overrides the +``SelectServers()`` method. The following example shows a simple custom server +selection class that selects servers with a ``ServerType`` of +``ServerType.ReplicaSetSecondary``: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ServerSelection.cs + :start-after: start-custom-class + :end-before: end-custom-class + :language: csharp + :dedent: + +You can then pass an instance of this class to the ``PreServerSelector`` or +``PostServerSelector`` property of a ``ClusterConfigurator`` instance, as shown in the +:ref:`csharp-server-selection-algorithm` section. + +Using Settings to Configure Server Selection +-------------------------------------------- + +You can specify the following server selection settings in your ``MongoClient`` object or +in your connection URI: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Setting + - Description + + * - ``LocalThreshold`` + - | The latency window for server eligibility. If a server's round trip takes longer + | than the fastest server's round-trip time plus this value, the server isn't + | eligible for selection. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 15 milliseconds + | **Connection URI Example**: ``localThresholdMS=0`` + + * - ``ReadPreference`` + - | The client's default read-preference settings. ``MaxStaleness`` represents the + | longest replication lag (in real time) that a secondary can experience and + | still be eligible for server selection. Specifying ``-1`` means no maximum. + | See :ref:`read preference ` for more information. + | + | **Data Type**: `ReadPreference <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadPreference.html>`__ + | **Default**: ``ReadPreference.Primary`` + | **Connection URI Example**: + + .. code-block:: none + :copyable: false + + readPreference=primaryPreferred + &maxStalenessSeconds=90 + &readPreferenceTags=dc:ny,rack:1 + + * - ``ServerSelectionTimeout`` + - | The length of time the driver tries to select a server before timing out. + | + | **Data Type**: ``TimeSpan`` + | **Default**: 30 seconds + | **Connection URI Example**: ``serverSelectionTimeoutMS=15000`` + +Troubleshooting +--------------- + +.. include:: /includes/troubleshooting/server-selection-timeout.rst + +API Documentation +----------------- + +To learn more about the classes and methods used in this guide, see the following API +documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ +- `ClusterConfigurator <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.ClusterConfigurator.html>`__ +- `ServerSelectors <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.html>`__ +- `IServerSelector <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.IServerSelector.html>`__ +- `SelectServer() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.IServerSelector.SelectServers.html>`__ diff --git a/source/fundamentals/stable-api.txt b/source/connect/connection-options/stable-api.txt similarity index 92% rename from source/fundamentals/stable-api.txt rename to source/connect/connection-options/stable-api.txt index 66384d50..e51768bb 100644 --- a/source/fundamentals/stable-api.txt +++ b/source/connect/connection-options/stable-api.txt @@ -15,13 +15,6 @@ :depth: 2 :class: singlecol -.. note:: - - The {+stable-api+} feature requires {+mdb-server+} 5.0 or later. - - You should use the {+stable-api+} feature only if all of the MongoDB - servers you're connecting to support this feature. - Overview -------- @@ -49,10 +42,10 @@ version of the {+stable-api+}. .. tip:: Once you've created a ``MongoClient``, you can't change its {+stable-api+} version. - If you need to run commands using more than one version of the + If you must run commands using more than one version of the {+stable-api+}, instantiate a separate client with that version. - If you need to run commands not covered by the {+stable-api+}, make sure the + If you must run commands not covered by the {+stable-api+}, make sure the "strict" option is disabled. See the section on :ref:`{+stable-api+} Options ` for more information. diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt new file mode 100644 index 00000000..fa97f8fe --- /dev/null +++ b/source/connect/connection-targets.txt @@ -0,0 +1,178 @@ +.. _csharp-connection-targets: + +========================== +Choose a Connection Target +========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, settings, client, load balancing, srv, dns + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use a connection string and ``MongoClient`` object +to connect to different types of MongoDB deployments. + +Atlas +----- + +To connect to a MongoDB deployment on Atlas, include the following elements +in your connection string: + +- URL of your Atlas cluster +- MongoDB username +- MongoDB password + +Then, pass your connection string to the ``MongoClient`` constructor. + +.. tip:: + + Follow the :atlas:`Atlas driver connection guide ` + to retrieve your connection string. + +When you connect to Atlas, we recommend using the {+stable-api+} client option to avoid +breaking changes when Atlas upgrades to a new version of {+mdb-server+}. +To learn more about the {+stable-api+} feature, see the :ref:`` guide. + +The following code shows how to use {+driver-short+} to connect to an Atlas cluster. The +code also uses the ``server_api`` option to specify a {+stable-api+} version. + +.. literalinclude:: /includes/fundamentals/code-examples/connection/AtlasConnection.cs + :language: csharp + :start-after: // start atlas connection + :end-before: // end atlas connection + +Local Deployments +----------------- + +To connect to a local MongoDB deployment, use ``localhost`` as the hostname. By +default, the ``mongod`` process runs on port 27017, though you can customize this for +your deployment. + +The following code shows how to use {+driver-short+} to connect to a local MongoDB +deployment: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/LocalConnection.cs + :language: csharp + :start-after: // start local connection + :end-before: // end local connection + +Replica Sets +------------ + +To connect to a replica set, specify the hostnames (or IP addresses) and +port numbers of the replica set members in your connection string. + +The following code shows how to use {+driver-short+} to connect to a replica set +that contains three hosts: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs + :language: csharp + :start-after: // start-replica-set-connection-list + :end-before: // end-replica-set-connection-list + +.. note:: Replica Set in Docker + + .. sharedinclude:: dbx/docker-replica-set.rst + +If you aren't able to provide a full list of hosts in the replica set, you can +specify one or more of the hosts in the replica set and instruct {+driver-short+} to +perform automatic discovery to find the others. To instruct the driver to perform +automatic discovery, perform one of the following actions: + +- Specify the name of the replica set as the value of the ``replicaSet`` parameter. +- Specify ``false`` as the value of the ``directConnection`` parameter. You can also omit + this parameter, as it defaults to ``false``. +- Specify more than one host in the replica set. + +In the following example, the driver uses a sample connection URI to connect to the +MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different +hosts, including ``host1``: + +.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs + :language: csharp + :start-after: // start-replica-set-connection-rs-name + :end-before: // end-replica-set-connection-rs-name + +.. note:: Specifying the Replica Set Name + + Although the driver can automatically discover replica set members without specifying + the hostnames of all members or the replica set name, we recommend specifying the + replica set name to avoid corner cases where the replica set will not initialize + correctly. + +The {+driver-short+} evenly load balances operations across deployments that are reachable +within the client's ``localThresholdMS`` value. To learn more about how the {+driver-short+} load +balances operations across multiple MongoDB deployments, see the +:ref:`csharp-server-selection` guide. + +.. note:: + + The ``MongoClient`` constructor is *non-blocking*. + When you connect to a replica set, the constructor returns immediately while the + client uses background threads to connect to the replica set. + + If you construct a ``MongoClient`` and immediately print the string representation + of its ``nodes`` attribute, the list might be empty while the client connects to + the replica set members. + +Connect to a Single Server +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To connect to a single server in a replica set rather than the entire replica set, specify +``false`` as the value of the ``directConnection`` connection option. You can do this in two ways: by passing +an argument to the ``MongoClient`` constructor or through a parameter in your connection string. Select the +:guilabel:`MongoClientSettings` or :guilabel:`Connection String` tab to see the corresponding code. + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: settings + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs + :language: csharp + :start-after: // start-replica-set-direct-connection-settings + :end-before: // end-replica-set-direct-connection-settings + + .. tab:: Connection String + :tabid: connection-string + + .. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs + :language: csharp + :start-after: // start-replica-set-direct-connection-string + :end-before: // end-replica-set-direct-connection-string + +DNS Service Discovery +--------------------- + +To use DNS service discovery to look up the DNS SRV record of the service you're connecting to, +specify the SRV connection format in your connection string. Additionally, if you enable +the SRV connection format, the {+driver-short+} automatically re-scans for new hosts without +having to change the client configuration. + +The following code shows a connection string that uses the SRV connection format: + +.. code-block:: csharp + + var uri = "mongodb+srv://" + +To learn more about the SRV connection format, see the :manual:`SRV Connection Format ` +entry in the {+mdb-server+} manual. + +API Documentation +----------------- + +To learn more about the types discussed in this guide, see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ diff --git a/source/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt similarity index 97% rename from source/connection-troubleshooting.txt rename to source/connect/connection-troubleshooting.txt index 68505cca..78032f65 100644 --- a/source/connection-troubleshooting.txt +++ b/source/connect/connection-troubleshooting.txt @@ -21,8 +21,6 @@ using the {+driver-long+} to connect to a MongoDB deployment. This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources: - - The :ref:`Frequently Asked Questions (FAQ) ` for the - {+driver-short+} - The :ref:`Issues & Help ` page, which has information about reporting bugs, contributing to the driver, and finding additional resources @@ -173,7 +171,7 @@ You can also set configuration settings by creating a ``MongoClientSettings`` object and passing that to the ``MongoClient`` constructor. You can use the ``Credential`` property to set the login credentials including specifying the authentication database. For more information about using ``MongoClientSettings`` -as well as some examples, see +and to see some examples, see :ref:`Using MongoClientSettings `. You can check if this is the issue by attempting to connect to a MongoDB @@ -254,7 +252,7 @@ The following section describes a method that may help resolve the issue. Check the Number of Connections ------------------------------- -If you need to create more open connections, increase ``MaxConnectionPoolSize``. For more +If you must create more open connections, increase ``MaxConnectionPoolSize``. For more information about checking the number of connections, see :ref:`Check the Number of Connections ` in the Error Sending Message section. @@ -284,7 +282,7 @@ time the driver spends attempting to establish the connection by using the :manual:`Timeout Options ` in the Server manual. -You should ensure the ``connectTimeoutMS`` setting is not lower than +Ensure the ``connectTimeoutMS`` setting is not lower than the highest network latency you have to a member of the set. If one of the secondary members has a latency of 10000 milliseconds, setting the ``connectTimeoutMS`` to 9000 prevents the driver from ever connecting to that @@ -306,7 +304,7 @@ You can set this option on the connection string. The following example sets You can also set configuration settings by creating a ``MongoClientSettings`` object and passing that to the ``MongoClient`` constructor. For more information -about using ``MongoClientSettings`` as well as some examples, see +about using ``MongoClientSettings`` and to see some examples, see :ref:`Using MongoClientSettings `. Check the Number of Connections diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt new file mode 100644 index 00000000..e4ef8697 --- /dev/null +++ b/source/connect/mongoclient.txt @@ -0,0 +1,118 @@ +.. _csharp-connect-to-mongodb: +.. _csharp-create-mongoclient: + +==================== +Create a MongoClient +==================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, Atlas, settings + :description: Learn how to create a MongoClient to connect to a MongoDB deployment URI and customize connection behavior. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +This guide shows you how to connect to a MongoDB instance or replica set +deployment by using the {+driver-short+}. + +Overview +-------- + +Connecting to a MongoDB deployment requires the following components: + +- **Connection URI**, also known as a *connection string*, which tells the {+driver-short+} + which MongoDB deployment to connect to. +- **MongoClient** object, which creates and sustains the connection to the MongoDB deployment + and lets you perform data operations. + +You can also specify connection settings in either of these components to customize the way +the {+driver-short+} behaves while connected to MongoDB. + +This guide shows you how to create a connection URI and use a ``MongoClient`` object +to connect to MongoDB. + +Connection URI +-------------- + +A standard connection URI includes the following components: + +.. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Component + - Description + + * - ``mongodb://`` + + - Required. A prefix that identifies this as a string in the + standard connection format. + + * - ``username:password`` + + - Optional. Authentication credentials. If you include these, the client + authenticates the user against the database specified in ``authSource``. + For more information about authentication settings, see + :ref:`csharp-authentication-mechanisms`. + + * - ``host[:port]`` + + - Required. The host and optional port number where MongoDB is running. If you don't + include the port number, the driver uses the default port ``27017``. + + * - ``/defaultauthdb`` + + - Optional. The authentication database to use if the + connection string includes ``username:password@`` + authentication credentials but not the ``authSource`` option. If you don't include + this component, the client authenticates the user against the ``admin`` database. + + * - ``?`` + + - Optional. A query string that specifies connection-specific + options as ``=`` pairs. See + :ref:`csharp-connection-options` for a full description of + these options. + +For more information about creating a connection string, see +:manual:`Connection Strings ` in the +MongoDB Server documentation. + +MongoClient +----------- + +To create a connection to MongoDB, pass a connection URI to the +``MongoClient`` constructor. In the following example, the driver uses a sample +connection URI to connect to a MongoDB deployment running on port ``27017`` of ``localhost``: + +.. code-block:: csharp + + const string uri = "mongodb://localhost:27017/"; + var client = new MongoClient(uri); + +Configure the Connection +------------------------ + +You can configure your connection in the following ways: + +- Specifying parameters in the connection URI +- Specifying settings on a ``MongoClientSettings`` or ``MongoUrlBuilder`` object + +To learn more about configuring your connection, see the +:ref:`csharp-connection-options` guide. + +API Documentation +----------------- + +To learn more about creating a ``MongoClient`` object with the {+driver-short+}, +see the following API documentation: + +- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__ +- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__ diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 00000000..6dfe9f55 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,25 @@ +.. _csharp-crud: + +=============== +CRUD Operations +=============== + +.. meta:: + :description: Learn how to run create, read, update, delete (CRUD) MongoDB operations by using the {+driver-long+}. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Insert Documents + Query Documents + Update One Document + Update Many Documents + Replace Documents + Delete Documents + Bulk Write Operations + Transactions + Store Large Files + Configure CRUD Operations + Geospatial Queries + Tutorial: Create a RESTful API \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/crud/bulk-write.txt similarity index 98% rename from source/fundamentals/crud/write-operations/bulk-write.txt rename to source/crud/bulk-write.txt index f204f1fb..ff3fc766 100644 --- a/source/fundamentals/crud/write-operations/bulk-write.txt +++ b/source/crud/bulk-write.txt @@ -497,8 +497,7 @@ parameters: * - ``collation`` - | *Optional.* The language collation to use when sorting results. See the - :manual:`{+mdb+server+} manual` - for more information. + :ref:`` section of this page for more information. | | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ | **Default:** ``null`` @@ -590,9 +589,8 @@ constructor accepts the following parameters: | **Data Type:** ``TDocument`` * - ``collation`` - - | *Optional.* The language collation to use when sorting results. See - the :manual:`{+mdb-server+} manual` - for more information. + - | *Optional.* The language collation to use when sorting results. See the + :ref:`` section of this page for more information. | | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ | **Default:** ``null`` @@ -652,9 +650,8 @@ parameters: | **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ * - ``collation`` - - | *Optional.* The language collation to use when sorting results. See - the :manual:`{+mdb-server+} manual` - for more information. + - | *Optional.* The language collation to use when sorting results. See the + :ref:`` section of this page for more information. | | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ | **Default:** ``null`` @@ -911,6 +908,13 @@ A ``ClientBulkWriteException`` object contains the following properties: | | **Data Type:** `Exception `__ +.. _csharp-bulk-write-collation: + +Collation +--------- + +.. include:: /includes/collation.rst + Additional Information ---------------------- diff --git a/source/fundamentals/read-write-configuration.txt b/source/crud/configure.txt similarity index 84% rename from source/fundamentals/read-write-configuration.txt rename to source/crud/configure.txt index 01ea55ed..bcaa7ddc 100644 --- a/source/fundamentals/read-write-configuration.txt +++ b/source/crud/configure.txt @@ -191,6 +191,47 @@ The following example sets the read preference to ``ReadPreference.Secondary`` f For more information about read preference, see :manual:`Read Preference ` in the {+mdb-server+} manual. +Retryable Reads and Writes +-------------------------- + +The {+driver-short+} automatically retries certain read and write operations a single time +if they fail due to a network or server error. + +You can explicitly disable retryable reads or retryable writes by setting the ``RetryReads`` +or ``RetryWrites`` options on a ``MongoClientSettings`` object and passing this object to the +``MongoClient`` constructor. You can also set the ``retryReads`` or ``retryWrites`` options +in a connection string. + +The following example disables retryable reads and writes for +a client. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection String` +tab to see the corresponding code. + +.. tabs:: + + .. tab:: MongoClientSettings + :tabid: mongoclientsettings + + .. literalinclude:: /includes/fundamentals/code-examples/ReplicaSetConfigs.cs + :start-after: start-retry-reads-writes + :end-before: end-retry-reads-writes + :emphasize-lines: 2-3 + :language: csharp + :dedent: + + .. tab:: Connection String + :tabid: connectionstring + + .. literalinclude:: /includes/fundamentals/code-examples/ReplicaSetConfigs.cs + :start-after: start-retry-reads-writes-connection-string + :end-before: end-retry-reads-writes-connection-string + :emphasize-lines: 1 + :language: csharp + :dedent: + +To learn more about supported retryable read and retryable write operations, see +:manual:`Retryable Reads ` +and :manual:`Retryable Writes ` in the {+mdb-server+} manual. + API Documentation ----------------- diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/crud/delete.txt similarity index 92% rename from source/fundamentals/crud/write-operations/delete.txt rename to source/crud/delete.txt index 8446ee53..d006f1fe 100644 --- a/source/fundamentals/crud/write-operations/delete.txt +++ b/source/crud/delete.txt @@ -47,7 +47,7 @@ classes as models: .. include:: /includes/convention-pack-note.rst This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster and load this sample data. Delete Operations @@ -140,9 +140,8 @@ following properties: * - ``Collation`` - | Gets or sets the type of language collation to use when sorting - results. See :manual:`the delete - statements` - for more information. + results. See the :ref:`` section of this page for more + information. * - ``Comment`` - | Gets or sets the comment for the operation. See :manual:`the delete command @@ -159,6 +158,13 @@ following properties: fields` for more information. +.. _csharp-delete-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Example ~~~~~~~ @@ -215,8 +221,10 @@ Additional Information For runnable examples of the delete operations, see the following usage examples: -- :ref:`csharp-delete-one` -- :ref:`csharp-delete-many` +- `DeleteOne() <{+example+}/delete-one/DeleteOne.cs>`__ +- `DeleteOneAsync() <{+example+}/delete-one/DeleteOneAsync.cs>`__ +- `DeleteMany() <{+example+}/delete-many/DeleteMany.cs>`__ +- `DeleteManyAsync() <{+example+}/delete-many/DeleteManyAsync.cs>`__ API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/geo.txt b/source/crud/geo.txt similarity index 99% rename from source/fundamentals/geo.txt rename to source/crud/geo.txt index a530076d..9a599202 100644 --- a/source/fundamentals/geo.txt +++ b/source/crud/geo.txt @@ -188,7 +188,7 @@ Examples -------- The following examples uses the MongoDB Atlas sample dataset. To obtain this sample -dataset, see :ref:`csharp-quickstart`. +dataset, see :ref:`csharp-get-started`. The examples use the ``theaters`` collection in the ``sample_mflix`` database from the sample dataset. The ``theaters`` collection contains a ``2dsphere`` index diff --git a/source/fundamentals/gridfs.txt b/source/crud/gridfs.txt similarity index 99% rename from source/fundamentals/gridfs.txt rename to source/crud/gridfs.txt index c5906346..3e12fa98 100644 --- a/source/fundamentals/gridfs.txt +++ b/source/crud/gridfs.txt @@ -690,7 +690,7 @@ code. .. note:: File Revisions The ``Delete()`` and ``DeleteAsync()`` methods support deleting only one file at a time. - If you want to delete each file revision, or files with different upload + To delete each file revision, or files with different upload times that share the same file name, collect the ``_id`` values of each revision. Then, pass each ``_id`` value in separate calls to the ``Delete()`` or ``DeleteAsync()`` method. diff --git a/source/fundamentals/crud/write-operations/insert.txt b/source/crud/insert.txt similarity index 94% rename from source/fundamentals/crud/write-operations/insert.txt rename to source/crud/insert.txt index 6d623a84..d6daf656 100644 --- a/source/fundamentals/crud/write-operations/insert.txt +++ b/source/crud/insert.txt @@ -72,7 +72,7 @@ classes as models: .. include:: /includes/convention-pack-note.rst This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster and load this sample data. The ``_id`` Field @@ -227,8 +227,8 @@ The following code uses the ``InsertMany()`` method to insert five new The ``InsertMany()`` method has no return value. You can verify that your documents were successfully inserted by executing a ``Find()`` -operation on the collection. For an example on how to find a document, -see :ref:`csharp-find-one`. +operation on the collection. For an example of how to find a document, +see :ref:`csharp-find`. .. _csharp-ordered-behavior: @@ -247,10 +247,8 @@ Assume you want to insert the following documents: If you attempt to insert these documents with default ``InsertManyOptions``, the driver throws a ``MongoBulkWriteException`` at the third -document because of the repeated ``_id`` value, but the documents before -the error-producing document are still inserted into your collection. - -If you look inside your collection, you should be able to see the following documents: +document because of the repeated ``_id`` value. The operation adds only the first two documents +to the collection: .. code-block:: json :copyable: false @@ -261,9 +259,7 @@ If you look inside your collection, you should be able to see the following docu If you set ``IsOrdered`` to ``false`` in your insert operation, the driver will continue to insert your documents even if some documents produce errors. With this modified insert behavior, the driver throws an exception but inserts all documents -that do not produce errors. - -If you look inside your collection, you should be able to see the following documents: +that do not produce errors: .. code-block:: json :copyable: false @@ -280,8 +276,10 @@ Additional Information For runnable examples of the insert operations, see the following usage examples: -- :ref:`csharp-insert-one` -- :ref:`csharp-insert-many` +- `InsertOne() <{+example+}/insert-one/InsertOne.cs>`__ +- `InsertOneAsync() <{+example+}/insert-one/InsertOneAsync.cs>`__ +- `InsertMany() <{+example+}/insert-many/InsertMany.cs>`__ +- `InsertManyAsync() <{+example+}/insert-many/InsertManyAsync.cs>`__ .. To learn more about performing the operations mentioned, see the .. following guides: diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 00000000..a5f9c99f --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,21 @@ +.. _csharp-crud-read-operations: +.. _csharp-crud-query: + +=============== +Read Operations +=============== + +.. meta:: + :description: Learn about the commands for running MongoDB read operations by using the {+driver-long+}. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Specify a Query + Find Documents + Specify Documents to Return + Specify Fields to Return + Count Documents + Distinct Field Values + Access Data from a Cursor \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/count.txt b/source/crud/query/count.txt similarity index 97% rename from source/fundamentals/crud/read-operations/count.txt rename to source/crud/query/count.txt index 30dc2a2b..76e8b486 100644 --- a/source/fundamentals/crud/read-operations/count.txt +++ b/source/crud/query/count.txt @@ -98,7 +98,8 @@ You can set the following properties in a ``CountOptions`` object: - Description * - ``Collation`` - - | The type of language collation to use when sorting results. + - | The type of language collation to use when sorting results. See the + :ref:`` section of this page for more information. | Default: ``null`` * - ``Hint`` @@ -132,6 +133,13 @@ You can set the following properties in a ``CountOptions`` object: CountOptions opts = new CountOptions(){Hint = "_id_"}; var count = collection.CountDocuments(filter, opts); +.. _csharp-count-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + .. _csharp-estimated-count: Estimated Count @@ -231,7 +239,6 @@ guides: - :ref:`csharp-specify-query` - :ref:`csharp-bson` - :ref:`csharp-guids` -- :ref:`csharp-builders` - :ref:`csharp-poco` API Documentation diff --git a/source/crud/query/cursors.txt b/source/crud/query/cursors.txt new file mode 100644 index 00000000..a3307199 --- /dev/null +++ b/source/crud/query/cursors.txt @@ -0,0 +1,179 @@ +.. _csharp-cursors: + +========================= +Access Data From a Cursor +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, results, oplog + +Overview +-------- + +In this guide, you can learn how to access data from a **cursor** by using the +{+driver-short+}. + +A cursor is a tool that returns the results of a read operation in iterable +batches. Because a cursor holds only a subset of documents at any given time, +cursors reduce both memory consumption and network bandwidth usage. + +You can retrieve a cursor by using the ``FindSync()`` or ``FindAsync()`` method. You can +also convert the results of the ``Find()`` method to a cursor by chaining the ``ToCursor()`` +or ``ToCursorAsync()`` method. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection +in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets `. +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, +see the :ref:`` tutorial. + +The examples on this page use the following ``Restaurant`` object to model the documents +in the ``restaurants`` collection: + +.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-restaurant-class + :end-before: end-restaurant-class + :language: csharp + +.. _csharp-cursors-iterate: + +Access Cursor Contents Iteratively +---------------------------------- + +To iterate over the contents of a cursor, use a ``foreach`` loop inside a ``using`` block. +The following example retrieves documents from the ``restaurants`` collection in which the +value of the ``name`` field is ``"Starbucks"``, then iterates over the results. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-iterate + :end-before: end-cursor-iterate + :language: csharp + :dedent: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-iterate-async + :end-before: end-cursor-iterate-async + :language: csharp + :dedent: + +The following example performs the same operation but uses the ``ToCursor()`` method. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-iterate-to-cursor + :end-before: end-cursor-iterate-to-cursor + :language: csharp + :dedent: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-iterate-to-cursor-async + :end-before: end-cursor-iterate-to-cursor-async + :language: csharp + :dedent: + +Retrieve All Documents +---------------------- + +.. warning:: + + If the number and size of documents returned by your query exceeds available + application memory, your program might crash. If you expect a large result + set, :ref:`access your cursor iteratively `. + +To retrieve all documents from a cursor, use the ``ToList()`` method, as shown in the +following example. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-to-list + :end-before: end-cursor-to-list + :language: csharp + :dedent: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-cursor-to-list-async + :end-before: end-cursor-to-list-async + :language: csharp + :dedent: + +Tailable Cursors +---------------- + +When querying on a :manual:`capped collection `, you +can use a **tailable cursor** that remains open after the client exhausts the +results in a cursor. To create a tailable cursor, create a ``FindOptions`` object and set the +``CursorType`` property to ``CursorType.TailableAwait``. Then, pass the ``FindOptions`` object +to one of the find operation methods. The following example shows how to create a tailable +cursor on a capped collection. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-tailable-cursor + :end-before: end-tailable-cursor + :language: csharp + :dedent: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs + :start-after: start-tailable-cursor-async + :end-before: end-tailable-cursor-async + :language: csharp + :dedent: + +API Documentation +----------------- + +To learn more about the methods and classes used in this guide, see the +following API documentation: + +- `FindSync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.FindSync.html>`__ +- `FindAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.FindAsync.html>`__ +- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ +- `IAsyncCursor <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursor-1.html>`__ +- `FindOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FindOptions.html>`__ diff --git a/source/fundamentals/crud/read-operations/distinct.txt b/source/crud/query/distinct.txt similarity index 96% rename from source/fundamentals/crud/read-operations/distinct.txt rename to source/crud/query/distinct.txt index 326c187c..640f38b5 100644 --- a/source/fundamentals/crud/read-operations/distinct.txt +++ b/source/crud/query/distinct.txt @@ -34,7 +34,7 @@ Sample Data The examples in this guide use the ``sample_restaurants.restaurants`` collection from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. The examples on this page uses the following ``Restaurant`` class to model the documents in the collection: @@ -180,7 +180,9 @@ describes the properties you can set on a ``DistinctOptions`` instance: - Description * - ``Collation`` - - | Sets the collation to use for the operation. + - | Sets the collation to use for the operation. See the + :ref:`` section of this page for more information. + | Default: ``null`` | **Data type**: `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.DistinctOptions.Collation.html>`__ * - ``MaxTime`` @@ -249,6 +251,13 @@ corresponding code. Angie'S Cafe Pizza ... +.. _csharp-distinct-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + API Documentation ----------------- diff --git a/source/fundamentals/crud/read-operations/retrieve.txt b/source/crud/query/find.txt similarity index 94% rename from source/fundamentals/crud/read-operations/retrieve.txt rename to source/crud/query/find.txt index d662fd76..de2005fb 100644 --- a/source/fundamentals/crud/read-operations/retrieve.txt +++ b/source/crud/query/find.txt @@ -1,4 +1,4 @@ -.. _csharp-retrieve: +.. _csharp-find: ============= Retrieve Data @@ -40,7 +40,7 @@ Sample Data The examples in this guide use the ``sample_restaurants.restaurants`` collection from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. The examples on this page use the following ``Restaurant``, ``Address``, and ``GradeEntry`` classes as models: @@ -215,7 +215,8 @@ You can configure the commonly used options with the following methods: ``Find()`` method uses the default batch size. * - ``Collation`` - - | Sets the collation options. + - | Sets the collation options. See the + :ref:`` section of this page for more information. * - ``Comment`` - | Sets the comment to the query to make looking in the profiler logs easier. @@ -229,6 +230,13 @@ You can configure the commonly used options with the following methods: To see a full list of available options, see `FindOptions Properties <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FindOptions.html>`__. +.. _csharp-find-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Example ~~~~~~~ @@ -278,8 +286,13 @@ To learn more about query filters, see :ref:`csharp-specify-query`. To learn how to specify queries using LINQ, see :ref:`csharp-linq`. -To view runnable examples of the ``Find()`` method, see the -:ref:`csharp-find-one` page. +For runnable examples of the find operations, see the following usage +examples: + +- `FindOne() <{+example+}/find-one/FindOne.cs>`__ +- `FindOneAsync() <{+example+}/find-one/FindOneAsync.cs>`__ +- `FindMany() <{+example+}/find-many/FindMany.cs>`__ +- `FindManyAsync() <{+example+}/find-many/FindManyAsync.cs>`__ API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/crud/query/project.txt b/source/crud/query/project.txt new file mode 100644 index 00000000..72f1ca2b --- /dev/null +++ b/source/crud/query/project.txt @@ -0,0 +1,510 @@ +.. _csharp-project: + +======================== +Specify Fields To Return +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, filter, project, select + +Overview +-------- + +In this guide, you can learn how to specify which fields to return from a read +operation by using a **projection**. A projection is a document that specifies +which fields MongoDB returns from a query. + +Sample Data +~~~~~~~~~~~ + +The examples on this page use the ``sample_mflix.movies`` collection +from the :atlas:`Atlas sample datasets `. To learn how to create a +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. + +The following class represents the documents in the ``sample_mflix.movies`` collection: + +.. literalinclude:: /includes/code-examples/projection/Movie.cs + :language: csharp + +.. note:: ConventionPack for Pascal Case + + The properties in the preceding class are named in Pascal case, but the + field names in the MongoDB collection use camel case. To account for this difference, + you can use the following code to register a ``ConventionPack`` when your + application starts: + + .. code-block:: csharp + + var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; + ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); + +.. _csharp-projection-methods: + +Create a Projection +------------------- + +To create a projection, perform the following steps: + +1. Use the ``Builders.Projection`` static property to create a + ``ProjectionDefinitionBuilder`` object, where ``TDocument`` represents the + C# class that the collection's documents map to. The ``ProjectionDefinitionBuilder`` class + provides a type-safe interface for defining a projection. + +#. Chain projection methods from the ``ProjectionDefinitionBuilder`` + object to specify which fields to include or exclude from the returned documents. + +#. Store the resulting ``ProjectionDefinition`` object in a variable. + +#. Pass the variable to the ``Project()`` method after performing the find or aggregation + operation. + +The following sections describe the methods that you can chain from your +``ProjectionDefinitionBuilder`` object. + +Field Projection Methods +------------------------ + +The following methods let you specify which fields to include or exclude from the returned +documents. + +ElemMatch +~~~~~~~~~ + +The ``ElemMatch()`` method limits the contents of an array field from the query results to +contain only the first element matching a specified condition. This is equivalent to projecting +an array element by using the ``$elemMatch`` operator in the {+query-api+}. + +For a code example that uses the ``ElemMatch()`` method, see +:manual:`$elemMatch ` +in the {+mdb-server+} manual. + +Expression +~~~~~~~~~~ + +The ``Expression()`` method lets you specify the structure of the returned documents +by using a lambda expression. This is equivalent to specifying the structure of the +returned documents in the ``$project`` aggregation stage in the {+query-api+}. + +For a code example that uses the ``Expression()`` method, see +:manual:`$project ` in the {+mdb-server+} manual. + +.. note:: ``Id`` Field Exclusion + + When you use a lambda expression to create a projection, the output + automatically excludes the ``Id`` field unless you explicitly include + it. + +Exclude +~~~~~~~ + +The ``Exclude()`` method lets you specify a field to exclude from the returned documents. +This is equivalent to excluding a field in the ``$project`` aggregation stage in the +{+query-api+}. You cannot combine inclusion and exclusion statements in a single +projection unless you are excluding the ``_id`` field. + +For a code example that uses the ``Exclude()`` method, see +:manual:`$project ` in the {+mdb-server+} manual. + +.. note:: Explicitly Exclude ``_id`` Field + + Returned documents include the ``_id`` field unless you explicitly exclude it. The + only exception to this is when you use the ``Expression()`` method to create a + projection. + +Include +~~~~~~~ + +The ``Include()`` method lets you specify a field to include in the returned documents. +This is equivalent to including a field in the ``$project`` aggregation stage in the +{+query-api+}. + +For a code example that uses the ``Include()`` method, see +:manual:`$project ` in the {+mdb-server+} manual. + +Slice +~~~~~ + +The ``Slice()`` method specifies the number of elements of a list or array to return in the query +result field. This is equivalent to using the ``$slice`` operator in the {+query-api+}. + +The following code example uses the ``Slice()`` method to return the first three elements +of the ``Cast`` list in the returned document's ``cast`` array: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/SliceExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start first three + :end-before: // end first three + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a1398f29313caabceb500" + }, + "title": "Back to the Future Part II", + "cast": [ + "Michael J. Fox", + "Christopher Lloyd", + "Lea Thompson" + ] + } + +To return elements from the end of a collection, pass a negative integer to the ``Slice()`` +method. The following code example returns the last three elements of the ``Cast`` list in +the returned document's ``cast`` array: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/SliceExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start last three + :end-before: // end last three + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a1398f29313caabceb500" + }, + "title": "Back to the Future Part II", + "cast": [ + "Lea Thompson", + "Thomas F. Wilson" + ] + } + +To skip a specified number of elements in a collection, pass the number of elements to skip +as the first parameter and the number of elements to return as the second +parameter. The following code example skips the first element in the +``Cast`` list and returns the next three elements in the ``cast`` array: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/SliceExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start skip first limit three + :end-before: // end skip first limit three + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a1398f29313caabceb500" + }, + "title": "Back to the Future Part II", + "cast": [ + "Christopher Lloyd", + "Lea Thompson", + "Thomas F. Wilson" + ] + } + +To learn more about the ``$slice`` operator, see +:manual:`$slice ` in the {+mdb-server+} manual. + +Metadata Projection Methods +--------------------------- + +The following methods let you specify which metadata fields to include or exclude +from the returned documents. Metadata fields are hidden by default. + +Meta +~~~~ + +The ``Meta()`` method lets you specify a metadata field to include in the returned +documents. This is equivalent to including a metadata field by using the +:manual:`$meta ` operator in the {+query-api+}. + +The following code example adds the ``textScore`` metadata field to the returned +documents as a field named ``score``: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/MetaExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start meta + :end-before: // end meta + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "..." + }, + "plot": "...", + "title": "...", + "score": "..." + } + +MetaSearchHighlights +~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/project/atlas-only-note.rst + +The ``MetaSearchHighlights()`` includes search highlights +in the returned documents. This is equivalent to projecting search highlights +by using a ``{ "$meta": "searchHighlights" }`` object in the {+query-api+}. +To retrieve search highlights, you must create a ``SearchHighlightOptions`` object that +specifies the search field, and then pass this object to the ``Search()`` method. + +The following code example retrieves search highlights for the ``plot`` field, then +includes these highlights in a property named ``Highlights`` in the returned documents: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/MetaExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start metaSearchHighlights + :end-before: // end metaSearchHighlights + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a13def29313caabdb5661" + }, + "plot": "She Can See Her Future, But Can't Escape Her Past.", + "title": "West", + "highlights": [ + { + "score": 1.286744475364685, + "path": "plot", + "texts": [ + { + "value": "She Can See Her ", + "type": "text" + }, + { + "value": "Future", + "type": "hit" + }, + { + "value": ", But Can't Escape Her Past.", + "type": "text" + } + ] + } + ] + } + +To learn more about search highlights, see +:atlas:`Highlight Search Terms in Results ` +in the Atlas documentation. + +MetaSearchScore +~~~~~~~~~~~~~~~ + +.. include:: /includes/project/atlas-only-note.rst + +The ``MetaSearchScore()`` method includes search scores in the returned +documents. This is equivalent to projecting search scores +by using a ``{ "$meta": "searchScore" }`` object in the {+query-api+}. + +The following code example projects each document's search score in a field named +``score``: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/MetaExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start metaSearchScore + :end-before: // end metaSearchScore + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a13def29313caabdb5661" + }, + "plot": "She Can See Her Future, But Can't Escape Her Past.", + "title": "West", + "score": 2.8259084224700928 + } + +To learn more about search scores, see +:atlas:`Score the Documents in the Returned Documents `. + +MetaSearchScoreDetails +~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/project/atlas-only-note.rst + +The ``MetaSearchScoreDetails()`` includes details about the search scores +in the returned documents. This is equivalent to projecting search score details +by using a ``{ "$meta": "searchScoreDetails" }`` object in the {+query-api+}. + +To retrieve score details, create a ``SearchOptions`` object with its +``ScoreDetails`` property set to ``true``, and then pass this object to the ``Search()`` method. +The following code example shows this process by projecting each document's search score +details in a field named ``searchScoreDetails``: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/MetaExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start metaSearchScoreDetails + :end-before: // end metaSearchScoreDetails + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a13def29313caabdb5661" + }, + ... + "scoreDetails": { + "value": 2.8259084224700928, + "description": "$type:string/plot:future [BM25Similarity], result of:", + "details": [ + { + "value": 2.8259084224700928, + "description": "score(freq=1.0), computed as boost * idf * tf from:", + "details": [ + ... + } + +To learn more about search score details, see +:atlas:`Return the Score Details ` +in the Atlas documentation. + +MetaSearchSequenceToken +~~~~~~~~~~~~~~~~~~~~~~~ + +.. include:: /includes/project/atlas-only-note.rst + +The ``MetaSearchSequenceToken()`` method includes a token in the returned documents +that represents a point in the search sequence. This is equivalent to projecting the search +sequence token by using a ``{ "$meta": "searchSequenceToken" }`` object in the +{+query-api+}. You can use this token to perform additional searches before or after the +specified point. + +The following code example projects each document's search sequence token in a property +named ``PaginationToken``: + +.. io-code-block:: + + .. input:: /includes/code-examples/projection/MetaExamples.cs + :language: csharp + :dedent: 8 + :start-after: // start metaSearchSequenceToken + :end-before: // end metaSearchSequenceToken + + .. output:: + :visible: false + :language: json + + { + "_id": { + "$oid": "573a13def29313caabdb5661" + }, + "plot": "She Can See Her Future, But Can't Escape Her Past.", + "title": "West", + "paginationToken": "CIeaARWv2zRAIg5aDFc6E97ykxPKq9tWYQ==" + } + +To learn more about search sequence tokens, see +:atlas:`Paginate Search Results ` + +MetaTextScore +~~~~~~~~~~~~~ + +The ``MetaTextScore()`` method includes the ``$text`` search scores in the returned documents. +This is equivalent to projecting the text search score by using a +``{ "$meta": "textScore" }`` object in the {+query-api+}. + +For a code example that uses the ``MetaTextScore()`` method, see +:manual:`$meta ` +in the {+mdb-server+} manual. + +MetaVectorSearchScore +~~~~~~~~~~~~~~~~~~~~~ + +.. note:: Atlas Vector Search Only + + This method is available only when projecting the results of an Atlas Vector Search. + +The ``MetaVectorSearchScore()`` method includes the Atlas Vector Search scores in the +returned documents. This is equivalent to projecting the Vector Search score by using a +``{ "$meta": "vectorSearchScore" }`` object in the {+query-api+}. + +For a code example that uses the ``MetaVectorSearchScore()`` method, see +:ref:`Atlas Vector Search `. + +To learn more about Atlas Vector Search scores, see +:atlas:`Score the Documents in the Returned Documents ` +in the Atlas documentation. + +SearchMeta +~~~~~~~~~~ + +.. include:: /includes/project/atlas-only-note.rst + +The ``SearchMeta()`` method includes a metadata results document. The structure of this +document depends on the type of the results. This is equivalent to projecting the +metadata results document by using the ``$searchMeta`` aggregation stage or the +``$$SEARCH_META`` aggregation variable in the {+query-api+}. + +For a code example that uses the ``SearchMeta()`` method, see +:atlas:`How to Use Facets with Atlas Search ` +in the Atlas documentation. + +To learn more about ``$searchMeta`` and ``$$SEARCH_META``, see the following Atlas +documentation: + +- :atlas:`$searchMeta ` +- :atlas:`$search with $$SEARCH_META ` + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- `Projection <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders-1.Projection.html>`_ +- `ProjectionDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.html>`__ +- `ElemMatch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.ElemMatch.html>`__ +- `Exclude() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Exclude.html>`__ +- `Expression() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Expression.html>`__ +- `Include() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Include.html>`__ +- `Meta() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Meta.html>`__ +- `MetaSearchHighlights <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaSearchHighlights.html>`__ +- `MetaSearchScore() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaSearchScore.html>`__ +- `MetaSearchScoreDetails() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaSearchScoreDetails.html>`__ +- `MetaSearchSequenceToken() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaSearchSequenceToken.html>`__ +- `MetaTextScore() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaTextScore.html>`__ +- `MetaVectorSearchScore() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.MetaVectorSearchScore.html>`__ +- `SearchMeta() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.SearchMeta.html>`__ +- `Slice() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Slice.html>`__ \ No newline at end of file diff --git a/source/crud/query/query-filter.txt b/source/crud/query/query-filter.txt new file mode 100644 index 00000000..fd936a88 --- /dev/null +++ b/source/crud/query/query-filter.txt @@ -0,0 +1,633 @@ +.. _csharp-specify-query: +.. _csharp-create-query-filter: + +===================== +Create a Query Filter +===================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: search, read, update, delete + +Overview +-------- + +In this guide, you can learn how to use the {+driver-long+} to create a **query filter**. +A query filter is an expression that specifies the documents to read, update, or delete +in a CRUD operation. You can use builder methods, available from the +``Builders.Filter`` static property, to create query filters and add +operations to them. + +.. include:: /includes/method-overloads.rst + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the following documents in a collection called +``guitars``: + +.. code-block:: json + + { "_id": 1, "make": "Fender", "models": ["Stratocaster", "Telecaster"], "establishedYear": 1946, "rating": 9 } + { "_id": 2, "make": "Gibson", "models": ["Les Paul", "SG", "Explorer"], "establishedYear": 1902, "rating": 8 } + { "_id": 3, "make": "PRS", "models": ["Silver Sky", "SE", "Custom"], "establishedYear": 1985, "rating": 9 } + { "_id": 4, "make": "Kiesel", "models": ["Ares", "Vader", "Solo"], "establishedYear": 2015 } + { "_id": 5, "make": "Ibanez", "models": ["RG", "AZ"], "establishedYear": 1957, "rating": 7 } + { "_id": 6, "make": "Strandberg", "models": ["Boden", "Salen"], "establishedYear": 1982 } + +The following ``Guitar`` class models the documents in this collection: + +.. literalinclude:: /includes/fundamentals/code-examples/specify-query/Guitar.cs + :language: csharp + :copyable: + :dedent: + +To run the code examples on this page, you must obtain a reference to the ``guitars`` +collection, as shown in the following example: + +.. code-block:: csharp + + var client = new MongoClient("localhost://27017"); + var guitarCollection = client.GetDatabase("example").GetCollection("guitars"); + +.. note:: + + The documents in the ``guitars`` collection use the camel-case naming + convention. The examples in this guide use a ``ConventionPack`` + to deserialize the fields in the collection into Pascal case and map them to + the properties in the ``Guitar`` class. + + To learn more creating and serializing custom classes, see the following pages: + + - :ref:`csharp-poco` + - :ref:`csharp-class-mapping` + - :ref:`csharp-serialization` + - :ref:`csharp-polymorphism` + +Find All Documents +------------------ + +An empty query filter matches all documents in a collection. The following example shows +how to create an empty query filter: + +.. code-block:: csharp + + var filter = Builders.Filter.Empty; + +Comparison Operators +-------------------- + +Comparison operators compare the query value to the value in a specified field. Some of +these methods have alternative syntax that you can use in place of the method, as shown +in the following example: + +.. code-block:: csharp + + var filter = Builders.Filter.Eq(g => g.Make, "Fender"); + var results = guitarCollection.Find(filter).ToList(); + + // Alternative syntax + var results = guitarCollection.Find(g => g.Make == "Fender").ToList();; + +The following table lists the {+driver-short+} methods for comparison operations +and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 20 40 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Alternative Syntax + - Description + - {+mdb-server+} Operator + + * - ``Eq()`` + - ``==`` + - Matches documents where the value of the specified field is equal to the query value. + - :manual:`$eq ` + + * - ``Gt()`` + - ``>`` + - Matches documents where the value of the specified field is greater than the query value. + - :manual:`$gt ` + + * - ``Gte()`` + - ``>=`` + - Matches documents where any element in the specified array field is greater than or + equal to the query value. + - :manual:`$gte ` + + * - ``In()`` + - N/A + - Matches documents where any element in the specified array field matches any value in + the query array. + - :manual:`$in ` + + * - ``Lt()`` + - ``<`` + - Matches documents where any element in the specified array field is less than the + query value. + - :manual:`$lt ` + + * - ``Lte()`` + - ``<=`` + - Matches documents where any element in the specified array field is less than or equal + to the query value. + - :manual:`$lte ` + + * - ``Ne()`` + - ``!=`` + - Matches documents where any element in the specified array field is not equal to + the query value. + - :manual:`$ne ` + + * - ``Nin()`` + - N/A + - Matches documents where one of the following is true: + + - None of the elements in the specified array field matches any of the values in the + query array. + - The specified field doesn't exist. + - :manual:`$nin ` + + * - ``StringIn()`` + - N/A + - Matches documents where the string value of the specified field matches any string + value in the query array. + - :manual:`$in ` + + * - ``StringNin()`` + - N/A + - Matches documents where the string value of the specified field doesn't match any + of the string values in the query array. + - :manual:`$in ` + +The following example calls the ``Find()`` method and passes a lambda filter, which +the driver translates to a query filter. The query matches all documents where the +``establishedYear`` field is greater than ``1985``. + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } + +The following example uses builders to create a query filter that matches the +same documents as the preceding example: + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } + +The following example calls the ``Find()`` method and passes a lambda expression, which +the driver translates to a query filter. The query matches all documents where the +``make`` field equals "Fender". + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } + +The following example uses builders to create a query filter that matches the +same documents as the preceding example: + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } + +Logical Operators +----------------- + +Logical operators combine two or more expressions and return results based on the results +of those expressions. These methods have alternative syntax that you can use in place of +the method, as shown in the following example: + +.. code-block:: csharp + + var builder = Builders.Filter; + var filter = builder.And( + builder.Gte(g => g.EstablishedYear, 1985), + builder.Ne(r => r.Make, "Kiesel")); + + var results = guitarCollection.Find(filter).ToList(); + + // Alternative syntax + var results = guitarCollection.Find( + g => g.EstablishedYear >= 1985 + && g.Make != "Kiesel") + .ToList(); + +The following table lists the {+driver-short+} methods for logical operations +and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 20 40 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Alternative Syntax + - Description + - {+mdb-server+} Operator + + * - ``And()`` + - ``&&`` + - Matches documents where all expressions evaluate to true. + - :manual:`$and ` + + * - ``Or()`` + - ``||`` + - Matches documents where one or more expressions evaluates to true. + - :manual:`$or ` + +The following example calls the ``Find()`` method and passes a lambda expression, +which the driver translates to a query filter. The query matches all documents where the +``establishedYear`` field is greater than or equal to ``1985``, and the ``make`` +field is not equal to "Kiesel". + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } + +The following example uses builders to create a query filter that matches the +same documents as the preceding example: + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } + +Array Operators +--------------- + +Array operators match documents based on the value or quantity of elements in an array +field. The following table lists the {+driver-short+} methods for array operations +and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 60 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + - {+mdb-server+} Operator + + * - ``All()`` + - Matches documents where the values in the specified array field match all query + values. + - :manual:`$all ` + + * - ``AnyEq()`` + - Matches documents where any element in the specified array field matches the + query value. + - :manual:`$elemMatch ` + + * - ``AnyGt()`` + - Matches documents where any element in the specified array field is greater than the + query value. + - :manual:`$elemMatch ` + + * - ``AnyGte()`` + - Matches documents where any element in the specified array field is greater than or + equal to the query value. + - :manual:`$elemMatch ` + + * - ``AnyIn()`` + - Matches documents where any element in the specified array field matches any value in + the query array. + - :manual:`$elemMatch ` + + * - ``AnyLt()`` + - Matches documents where any element in the specified array field is less than the + query value. + - :manual:`$elemMatch ` + + * - ``AnyLte()`` + - Matches documents where any element in the specified array field is less than or + equal to the query value. + - :manual:`$elemMatch ` + + * - ``AnyNe()`` + - Matches documents where any element in the specified array field is not equal to + the query value. + - :manual:`$elemMatch ` + + * - ``AnyNin()`` + - Matches documents where one of the following is true: + + - Any element in the specified array field isn't in the query array. + - The specified field doesn't exist. + - :manual:`$elemMatch ` + + * - ``AnyStringIn()`` + - Matches documents where any string element in the specified array field matches any + string value in the query array. + - :manual:`$elemMatch ` + + * - ``AnyStringNin()`` + - Matches documents where one of the following is true: + + - Any string element in the specified array field isn't in the query array. + - The specified field doesn't exist. + - :manual:`$elemMatch ` + + * - ``ElemMatch()`` + - Matches documents where any element in the specified array field matches the + query criteria. + - :manual:`$elemMatch ` + + * - ``Size()`` + - Matches documents where the specified array field is the specified size. + - :manual:`$size ` + + * - ``SizeGt()`` + - Matches documents where the specified array field is larger than the specified size. + - :manual:`$size ` + + * - ``SizeGte()`` + - Matches documents where the specified array field is larger than or equal to the + specified size. + - :manual:`$size ` + + * - ``SizeLt()`` + - Matches documents where the specified array field is smaller than the specified size. + - :manual:`$size ` + + * - ``SizeLte()`` + - Matches documents where the specified array field is smaller than or equal to the + specified size. + - :manual:`$size ` + +The following example uses builders to create a query filter that matches all +documents that have exactly three elements in the ``models`` field: + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } + { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } + { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } + +Element Operators +----------------- + +Element operators match document query data based on the presence or type of a field. +The following table lists the {+driver-short+} methods for element operations +and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 60 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + - {+mdb-server+} Operator + + * - ``Exists()`` + - Matches documents that contain or don't contain a specified field, including + documents where the field value is ``null``. + - :manual:`$exists ` + + * - ``Type()`` + - Matches documents where the value of the specified field is an instance of the + specified BSON types. + - :manual:`$type ` + +The following example uses builders to create a query filter that matches all +documents that have a ``rating`` field: + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } + { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } + { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } + { "_id" : 5, "make" : "Ibanez", "models" : ["RG", "AZ"], "establishedYear" : 1957, "rating" : 7 } + +Evaluation Operators +-------------------- + +Evaluation operators analyze data in individual fields or all documents in the collection. +The following table lists the {+driver-short+} methods for +evaluation operations and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 60 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + - {+mdb-server+} Operator + + * - ``JsonSchema()`` + - Matches documents that satisfy the specified JSON schema. + - :manual:`$jsonSchema ` + + * - ``Mod()`` + - Matches documents where the value of the specified field divided by a divisor has the + specified remainder (modulo). + - :manual:`$mod ` + + * - ``RegEx()`` + - Matches documents where the value of the specified field matches a specified regular + expression. + - :manual:`$regex ` + + * - ``Where()`` + - Use to pass either a string containing a JavaScript expression or a full JavaScript + function to the query system. + - :manual:`$where ` + +The following example uses builders to create a query filter that matches all +documents that have a value in the ``make`` field that starts with the letter +"G": + +.. io-code-block:: + :copyable: + + .. input:: /includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs + :language: csharp + + .. output:: + :language: json + :visible: false + + { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } + +Geospatial Operators +-------------------- + +Geospatial operators return data based on geospatial expression conditions. +The following table lists the {+driver-short+} methods for +geospatial operations and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 60 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + - {+mdb-server+} Operator + + * - ``GeoIntersects()`` + - Matches documents whose geospatial data intersects with a specified + `GeoJsonObject <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.GeoJsonObjectModel.GeoJsonObject-1.html>`__. + - :manual:`$geoIntersects ` + + * - ``GeoWithin()`` + - Matches documents whose geospatial data is entirely within the specified shape. + - :manual:`$geoWithin ` + + * - ``GeoWithinBox()`` + - Matches documents whose geospatial data is entirely within the specified box. + - :manual:`$geoWithin `, :manual:`$box ` + + * - ``GeoWithinCenter()`` + - Matches documents whose geospatial data is entirely within the specified circle. + - :manual:`$geoWithin `, :manual:`$center ` + + * - ``GeoWithinCenterSphere()`` + - Matches documents whose geospatial data is entirely within the specified sphere. + - :manual:`$geoWithin `, :manual:`$centerSphere ` + + * - ``GeoWithinPolygon()`` + - Matches documents whose geospatial data is entirely within the specified polygon. + - :manual:`$geoWithin `, :manual:`$polygon ` + + * - ``Near()`` + - Specifies a point for which a geospatial query returns the documents from nearest to + farthest. + - :manual:`$near ` + + * - ``NearSphere()`` + - Specifies a point for which a geospatial query returns the documents from nearest to + farthest in spherical geometry. + - :manual:`$nearSphere ` + +Bitwise Operators +----------------- + +Bitwise operators matches documents based on bit-position conditions. +The following table lists the {+driver-short+} methods for +bitwise operations and the equivalent {+mdb-server+} operators: + +.. list-table:: + :widths: 20 60 20 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + - {+mdb-server+} Operator + + * - ``BitsAllClear()`` + - Matches documents where all the specified bit positions are clear (``0``) in + the specified field. + - :manual:`$bitsAllClear ` + + * - ``BitsAllSet()`` + - Matches documents where all the specified bit positions are set (``1``) in + the specified field. + - :manual:`$bitsAllSet ` + + * - ``BitsAnyClear()`` + - Matches documents where any of the specified bit positions are clear (``0``) in + the specified field. + - :manual:`$bitsAnyClear ` + + * - ``BitsAnySet()`` + - Matches documents where any of the specified bit positions are set (``1``) in + the specified field. + - :manual:`$bitsAnySet ` + +Other Operators +--------------- + +The {+driver-short+} also provides the following methods that create filter definitions: + +.. list-table:: + :widths: 40 60 + :header-rows: 1 + + * - {+driver-short+} Method + - Description + + * - ``OfType()`` + - Matches documents of a type derived from the specified type. You can use overloads + of this method to specify additional query criteria. + + * - ``Text()`` + - Matches documents with a field that contains the specified string. + +Additional Information +---------------------- + +For more information about any of the driver methods on this page, see the +API documentation for the +`FilterDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinitionBuilder-1.html>`__ +class. \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/specify-documents-to-return.txt b/source/crud/query/specify-documents.txt similarity index 97% rename from source/fundamentals/crud/read-operations/specify-documents-to-return.txt rename to source/crud/query/specify-documents.txt index 99e7d85f..3b660182 100644 --- a/source/fundamentals/crud/read-operations/specify-documents-to-return.txt +++ b/source/crud/query/specify-documents.txt @@ -13,9 +13,10 @@ Specify Documents to Return .. facet:: :name: genre :values: reference - + .. meta:: :keywords: read, paginate, pagination, order, code example + :description: Learn how to specify queries using the MongoDB .NET/C# Driver, including creating query filters and using comparison, logical, array, element, and evaluation operators. Overview -------- @@ -181,7 +182,7 @@ skipping the first ``10`` documents: .. output:: :visible: false - + Acqua Acqua Restaurant Acqua Santa @@ -203,7 +204,7 @@ skipping the first ``10`` documents: Additional Information ---------------------- -For more information about retrieving documents, see the :ref:`csharp-retrieve` guide. +For more information about retrieving documents, see the :ref:`csharp-find` guide. For more information about specifying a query, see the :ref:`csharp-specify-query` guide. diff --git a/source/fundamentals/crud/write-operations/replace.txt b/source/crud/replace.txt similarity index 95% rename from source/fundamentals/crud/write-operations/replace.txt rename to source/crud/replace.txt index 856512fc..f1e91c7f 100644 --- a/source/fundamentals/crud/write-operations/replace.txt +++ b/source/crud/replace.txt @@ -156,8 +156,8 @@ The ``ReplaceOptions`` class contains the following properties: * - ``Collation`` - Specifies the kind of language collation to use when sorting - results. See :manual:`the {+mdb-server+} manual ` - for more information on collation. + results. See the :ref:`` section of this page for more + information. **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ @@ -234,6 +234,13 @@ code. :start-after: // start-replace-one-async-with-options :end-before: // end-replace-one-async-with-options +.. _csharp-replace-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Return Value ~~~~~~~~~~~~ @@ -276,6 +283,15 @@ The ``ReplaceOneResult`` class contains the following properties: **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ +Additional Information +---------------------- + +For runnable examples of the replace operation, see the following usage +examples: + +- `ReplaceOne() <{+example+}/replace-one/ReplaceOne.cs>`__ +- `ReplaceOneAsync() <{+example+}/replace-one/ReplaceOneAsync.cs>`__ + API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/crud/restful-api-tutorial.txt b/source/crud/restful-api-tutorial.txt similarity index 99% rename from source/fundamentals/crud/restful-api-tutorial.txt rename to source/crud/restful-api-tutorial.txt index 33520910..a0aad48c 100644 --- a/source/fundamentals/crud/restful-api-tutorial.txt +++ b/source/crud/restful-api-tutorial.txt @@ -372,6 +372,6 @@ To learn more about the operations discussed in this tutorial, see the following guides: - :ref:`csharp-insert-guide` -- :ref:`csharp-retrieve` +- :ref:`csharp-find` - :ref:`csharp-update-one` - :ref:`csharp-delete-guide` diff --git a/source/fundamentals/transactions.txt b/source/crud/transactions.txt similarity index 76% rename from source/fundamentals/transactions.txt rename to source/crud/transactions.txt index 07b9b68b..40990745 100644 --- a/source/fundamentals/transactions.txt +++ b/source/crud/transactions.txt @@ -1,15 +1,15 @@ .. _csharp-transactions: -============ -Transactions -============ +================================ +Batch Operations in Transactions +================================ .. facet:: :name: genre :values: reference .. meta:: - :keywords: code example, multi-document + :keywords: code example, multi-document, atomic, acid :description: Learn to perform transactions using the MongoDB .NET/C# Driver, ensuring data consistency and handling errors with session-based operations. .. contents:: On this page @@ -28,21 +28,33 @@ transaction is committed. If any operation in the transaction returns an error, the driver cancels the transaction and discards all data changes before they ever become visible. +MongoDB guarantees that the data involved in your transaction operations remains +consistent, even if the operations encounter unexpected errors. + +Sessions +-------- + In MongoDB, transactions run within logical **sessions**. A :manual:`session ` is a grouping of related read or write operations that you intend to run sequentially. Sessions -enable :manual:`causal consistency -` for a +enable causal consistency for a group of operations or allow you to execute operations in an -:website:`ACID transaction `. MongoDB -guarantees that the data involved in your transaction operations remains -consistent, even if the operations encounter unexpected errors. +:website:`ACID transaction `. When using the {+driver-short+}, you can create a new session from a ``MongoClient`` instance as an ``IClientSession`` type. We recommend that you reuse your client for multiple sessions and transactions instead of instantiating a new client each time. +The following example shows how to create a session by calling the ``StartSession()`` +method: + +.. code-block:: csharp + :copyable: true + + var client = new MongoClient("mongodb://localhost:27017"); + var session = client.StartSession(); + .. warning:: Use an ``IClientSession`` only with the ``MongoClient`` (or associated @@ -50,6 +62,90 @@ instantiating a new client each time. ``IClientSession`` with a different ``MongoClient`` results in operation errors. +ClientSessionOptions +~~~~~~~~~~~~~~~~~~~~ + +You can customize the behavior of your session by passing an instance of the +``ClientSessionOptions`` class to the ``StartSession()`` method. The following table +describes the properties that you can set on a ``ClientSessionOptions`` object: + +.. list-table:: + :widths: 35 65 + :header-rows: 1 + + * - Property + - Description + + * - ``CausalConsistency`` + - | Specifies whether the session is causally consistent. In a causally consistent session, + the driver executes operations in the order they were issued. To learn more, see + :ref:``. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``true`` + + * - ``DefaultTransactionOptions`` + - | Specifies the default transaction options for the session. This includes the maximum commit + time, read concern, read preference, and write concern. + | + | **Data Type**: `TransactionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.TransactionOptions.html>`__ + | **Default**: ``null`` + + * - ``Snapshot`` + - | Specifies whether the driver performs snapshot reads. To learn more about snapshot + reads, see :manual:`Read Concern "snapshot" ` + in the {+mdb-server+} manual. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + +The following code example shows how to create a session with custom options: + +.. code-block:: csharp + :copyable: true + + var client = new MongoClient("mongodb://localhost:27017"); + var sessionOptions = new ClientSessionOptions + { + CausalConsistency = true, + DefaultTransactionOptions = new TransactionOptions( + readConcern: ReadConcern.Available, + writeConcern: WriteConcern.Acknowledged) + }; + + var session = client.StartSession(sessionOptions); + +.. _csharp-causal-consistency: + +Causal Consistency +~~~~~~~~~~~~~~~~~~ + +.. sharedinclude:: dbx/causal-consistency.rst + + .. replacement:: insert-one-method + + ``InsertOne()`` + + .. replacement:: update-one-method + + ``UpdateOne()`` + + .. replacement:: find-one-method + + ``Find()`` + + .. replacement:: delete-one-method + + ``DeleteOne()`` + + .. replacement:: majority-rc + + ``ReadConcern.Majority`` + + .. replacement:: majority-wc + + ``WriteConcern.WMajority`` + Methods ------- @@ -66,7 +162,7 @@ tabs to learn about the methods to manage your transaction: :tabid: synchronous-methods .. list-table:: - :widths: 40 60 + :widths: 30 70 :header-rows: 1 * - Method @@ -232,3 +328,4 @@ guide, see the following API Documentation: - `CommitTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransaction.html>`__ / `CommitTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.CommitTransactionAsync.html>`__ - `WithTransaction() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransaction.html>`__ / `WithTransactionAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IClientSession.WithTransactionAsync.html>`__ - `TransactionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.TransactionOptions.html>`__ +- `CausalConsistency <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientSessionOptions.CausalConsistency.html>`__ \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-many.txt b/source/crud/update-many.txt similarity index 91% rename from source/fundamentals/crud/write-operations/update-many.txt rename to source/crud/update-many.txt index 7e219246..4fca9692 100644 --- a/source/fundamentals/crud/write-operations/update-many.txt +++ b/source/crud/update-many.txt @@ -20,8 +20,8 @@ Update Many .. toctree:: :caption: Update Documents - Fields - Arrays + Fields + Arrays .. include:: /includes/page-templates/update/update.rst @@ -57,9 +57,10 @@ Update Many multiple documents - .. replacement:: usage-examples-link + .. replacement:: usage-examples-links - :ref:`csharp-examples-update-many` + - `UpdateMany() <{+example+}/update-many/UpdateMany.cs>`__ + - `UpdateManyAsync() <{+example+}/update-many/UpdateManyAsync.cs>`__ .. replacement:: sync-api-link @@ -131,6 +132,4 @@ Update Many :copyable: true :dedent: :start-after: // start-pipeline-async - :end-before: // end-pipeline-async - - + :end-before: // end-pipeline-async \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations/update-many/arrays.txt b/source/crud/update-many/arrays.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update-many/arrays.txt rename to source/crud/update-many/arrays.txt diff --git a/source/fundamentals/crud/write-operations/update-many/fields.txt b/source/crud/update-many/fields.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update-many/fields.txt rename to source/crud/update-many/fields.txt diff --git a/source/fundamentals/crud/write-operations/update-one.txt b/source/crud/update-one.txt similarity index 91% rename from source/fundamentals/crud/write-operations/update-one.txt rename to source/crud/update-one.txt index 5580b2b2..6d3a4c2c 100644 --- a/source/fundamentals/crud/write-operations/update-one.txt +++ b/source/crud/update-one.txt @@ -20,8 +20,8 @@ Update One .. toctree:: :caption: Update Documents - Fields - Arrays + Fields + Arrays .. include:: /includes/page-templates/update/update.rst @@ -57,9 +57,10 @@ Update One a single document - .. replacement:: usage-examples-link + .. replacement:: usage-examples-links - :ref:`csharp-examples-update-one` + - `UpdateOne() <{+example+}/update-one/UpdateOne.cs>`__ + - `UpdateOneAsync() <{+example+}/update-one/UpdateOneAsync.cs>`__ .. replacement:: sync-api-link diff --git a/source/fundamentals/crud/write-operations/update-one/arrays.txt b/source/crud/update-one/arrays.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update-one/arrays.txt rename to source/crud/update-one/arrays.txt diff --git a/source/fundamentals/crud/write-operations/update-one/fields.txt b/source/crud/update-one/fields.txt similarity index 100% rename from source/fundamentals/crud/write-operations/update-one/fields.txt rename to source/crud/update-one/fields.txt diff --git a/source/fundamentals/database-collection.txt b/source/databases-collections.txt similarity index 99% rename from source/fundamentals/database-collection.txt rename to source/databases-collections.txt index d62658dc..a9bab87d 100644 --- a/source/fundamentals/database-collection.txt +++ b/source/databases-collections.txt @@ -1,4 +1,5 @@ .. _csharp-db-coll: +.. _csharp-databases-collections: ========================= Databases and Collections @@ -18,9 +19,6 @@ Databases and Collections :depth: 2 :class: singlecol -.. toctree:: - /fundamentals/databases-collections/run-command - Overview -------- diff --git a/source/document-formats.txt b/source/document-formats.txt new file mode 100644 index 00000000..aec17602 --- /dev/null +++ b/source/document-formats.txt @@ -0,0 +1,29 @@ +.. _csharp-document-formats: + +================ +Document Formats +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: bson, json, object, notation, read, write + +.. toctree:: + :caption: Document Formats + + BSON + Extended JSON + +Learn about using different document formats with the {+driver-short+} in the following guides: + +- :ref:`csharp-bson` +- :ref:`csharp-extended-json` \ No newline at end of file diff --git a/source/fundamentals/bson.txt b/source/document-formats/bson.txt similarity index 85% rename from source/fundamentals/bson.txt rename to source/document-formats/bson.txt index 2ede326c..5525c0e5 100644 --- a/source/fundamentals/bson.txt +++ b/source/document-formats/bson.txt @@ -9,6 +9,9 @@ BSON Operations .. default-domain:: mongodb +.. meta:: + :keywords: document, BSON, serializer + .. contents:: On this page :local: :backlinks: none @@ -47,7 +50,8 @@ The code samples in this guide use the following BSON document as an example: Create a BSON Document ---------------------- -To build a BSON document in {+language+}, create an instance of the ``BsonDocument`` class. +To build a representation of a BSON document in {+language+}, create an instance of the +``BsonDocument`` class. The ``BsonDocument`` constructor accepts ``BsonElement`` arguments that map to the fields and values in the document. Each ``BsonElement`` can be either an instance of the ``BsonElement`` class or a field-value pair inside curly braces ( ``{}`` ). @@ -98,8 +102,8 @@ write to a file, perform the following steps: #. For each BSON document and subdocument you want to create, call ``WriteStartDocument()``. #. Within each BSON document and subdocument, call ``WriteName()`` to set the field - name and the appropriate ``Write*`` method to set its value. Each data type has a - dedicated ``Write*`` method that you should use. + name and the appropriate ``Write*`` method to set its value. Use the + dedicated ``Write*`` method that corresponds to each data type. #. To start and end arrays, use ``WriteStartArray()`` and ``WriteEndArray()``. #. At the end of each document and subdocument, call ``WriteEndDocument()``. @@ -215,6 +219,22 @@ BSON document stored in ``myFile.bson``: ``System.IO.Stream`` object. This means that you can read or write any location that can be accessed by a stream. +Read and Write Other Formats +---------------------------- + +The preceding examples show how to read and write BSON data by using the +``BsonBinaryReader`` and ``BsonBinaryWriter`` classes. These classes implement the +``IBsonReader`` and ``IBsonWriter`` interfaces. To read and write data in other formats, +the {+driver-short+} provides the following alternative implementations of the ``IBsonReader`` +and ``IBsonWriter`` interfaces: + +- ``JsonReader`` and ``JsonWriter``: Read and write JSON data +- ``BsonDocumentReader`` and ``BsonDocumentWriter``: Read and write BSON data + contained in a ``BsonDocument`` object + +Because these classes implement the same interfaces, you can call their methods in the same way +as the preceding ``BsonBinaryReader`` and ``BsonBinaryWriter`` examples. + .. _csharp-bson-api: API Documentation @@ -227,3 +247,5 @@ guide, see the following API documentation: - `BsonElement <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonElement.html>`__ - `BsonBinaryReader <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.BsonBinaryReader.html>`__ - `BsonBinaryWriter <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.BsonBinaryWriter.html>`__ +- `IBsonReader <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.IBsonReader.html>`__ +- `IBsonWriter <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.IBsonWriter.html>`__ \ No newline at end of file diff --git a/source/document-formats/extended-json.txt b/source/document-formats/extended-json.txt new file mode 100644 index 00000000..010910ff --- /dev/null +++ b/source/document-formats/extended-json.txt @@ -0,0 +1,90 @@ +.. _csharp-extended-json: + +============= +Extended JSON +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code examples, bson, relaxed, canonical, legacy + +.. sharedinclude:: dbx/extended-json.rst + + .. replacement:: driver-specific-text-relaxed + + The {+driver-short+} uses Relaxed mode by default. + + +Read Extended JSON +------------------ + +You can read an Extended JSON documents into a {+language+} object by using the +``BsonDocument.Parse()`` method. The following example reads an +Extended JSON document into a ``BsonDocument`` object: + +.. io-code-block:: + + .. input:: /includes/fundamentals/code-examples/ExtendedJson.cs + :language: csharp + :start-after: start-read-ejson + :end-before: end-read-ejson + :dedent: + + .. output:: + :visible: false + + { "_id" : { "$oid" : "573a1391f29313caabcd9637" }, "createdAt" : { "$date" : "1970-01-19T12:51:39.609Z" }, "numViews" : 36520312 } + +Write Extended JSON +------------------- + +You can write an Extended JSON string by calling the ``ToJson()`` method on a +``BsonDocument`` object or custom class. You must specify a ``JsonWriterSettings`` object +with the ``OutputMode`` property set to the desired Extended JSON format as a parameter. + +Consider the following custom class: + +.. literalinclude:: /includes/fundamentals/code-examples/ExtendedJson.cs + :language: csharp + :start-after: start-custom-class + :end-before: end-custom-class + +The following example outputs an instance of ``MyDocument`` in +Extended JSON format by specifying the ``CanonicalExtendedJson`` value as an ``OutputMode`` +property: + +.. io-code-block:: + + .. input:: /includes/fundamentals/code-examples/ExtendedJson.cs + :language: csharp + :start-after: start-write-ejson + :end-before: end-write-ejson + :dedent: + + .. output:: + :visible: false + + { "_id" : { "$oid" : "68094769744af81f368ff1c1" }, "CreatedAt" : { "$date" : { "$numberLong" : "1745438569994" } }, "NumViews" : { "$numberLong" : "1234567890" } } + +API Documentation +----------------- + +To learn more about the methods and classes you can use to work with JSON documents, see the following API +documentation: + +- `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ +- `BsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.html>`__ +- `ToJson() <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonExtensionMethods.ToJson.html>`__ +- `JsonWriter <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonWriter.html>`__ +- `JsonReader <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonReader.html>`__ +- `JsonWriterSettings <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonWriterSettings.html>`__ +- `JsonOutputMode <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.IO.JsonOutputMode.html>`__ \ No newline at end of file diff --git a/source/faq.txt b/source/faq.txt deleted file mode 100644 index a838d20b..00000000 --- a/source/faq.txt +++ /dev/null @@ -1,330 +0,0 @@ -.. _csharp-faq: - -========================== -Frequently Asked Questions -========================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: .NET, questions, errors, problems - :description: Find answers to common questions about the C# driver, including connection pooling, server selection timeouts, and serialization options. - -This page contains frequently asked questions and their corresponding answers. - -.. tip:: - - If you can't find an answer to your problem on this page, - see the :ref:`csharp-issues-help` page for next steps and more - resources. - -Why Am I Getting Errors While Connecting to MongoDB? ----------------------------------------------------- - -If you have trouble connecting to a MongoDB deployment, see -the :ref:`Connection Troubleshooting Guide ` -for possible solutions. - -.. _csharp-faq-connection-pool: - -How Does Connection Pooling Work in the {+driver-short+}? ---------------------------------------------------------- - -Every ``MongoClient`` instance has a built-in connection pool for each server -in your MongoDB topology. Connection pools open sockets on demand to -support concurrent MongoDB operations in your multi-threaded application. - -The maximum size of each connection pool is set by the ``MaxConnectionPoolSize`` option, which -defaults to ``100``. If the number of in-use connections to a server reaches -the value of ``MaxConnectionPoolSize``, the next request to that server will wait -until a connection becomes available. The following diagram illustrates a high-level view -of how the ``MongoClient`` manages a connection pool: - -.. figure:: /includes/figures/CMAP_diagram.svg - :alt: CMAP diagram - -In addition to the sockets needed to support your application's threads, -each ``MongoClient`` instance opens two additional sockets per server -in your MongoDB topology for monitoring the server's state. -For example, a client connected to a three-node replica set opens six -monitoring sockets. If the application uses the default setting for -``MaxConnectionPoolSize`` and only queries the primary (default) node, then -there can be at most ``106`` total connections in use. If the -application uses a :ref:`read preference ` to query the -secondary nodes, those connection pools grow and there can be -``306`` total connections. - -To support high numbers of concurrent MongoDB threads -within one process, you can increase ``MaxConnectionPoolSize``. - -The driver has a wait queue that limits the number of threads that can -wait for a connection. The size of the wait queue is determined by the -``WaitQueueMultiple`` option, which defaults to ``5``. To calculate the -maximum wait queue size, the driver multiplies ``WaitQueueMultiple`` by -``MaxConnectionPoolSize``. If you use the default value for each option, -the wait queue size will be ``500``. You can also set the wait queue -size by specifying the ``WaitQueueSize`` option, which overrides the -other settings. However, we do not recommend changing the wait queue -size from the default. - -Connection pools are rate-limited. The ``MaxConnecting`` setting -determines the number of connections that the pool can create in -parallel at any time. For example, if the value of ``MaxConnecting`` is -``2``, the third thread that attempts to concurrently check out a -connection succeeds only in one of the following cases: - -- One of the first two threads finishes creating a connection. -- An existing connection is checked back into the pool. -- The driver's ability to reuse existing connections improves due to - rate-limits on connection creation. - -You can set the minimum number of concurrent connections to -each server by using the ``MinConnectionPoolSize`` option, which -defaults to ``0``. The connection pool will be initialized with this -number of sockets. If errors cause any sockets to close and the -total number of sockets (both in-use and idle) drops below the minimum, -the driver opens more sockets until the number reaches the minimum. - -You can set the maximum number of milliseconds that a connection can -remain idle in the pool by using the ``MaxConnectionIdleTime`` option. -Once a connection is idle for ``MaxConnectionIdleTime``, the driver -removes it. This option defaults to 10 minutes. If the pool size falls -below ``MinConnectionPoolSize``, the driver removes *and* replaces the -idle connection. - -``MongoClient`` also has the ``MaxConnectionLifeTime`` option, which -specifies the length of time, 30 minutes by default, that a connection -can be pooled before expiring. - -The following default configuration for a ``MongoClient`` works for most -applications: - -.. code-block:: csharp - - var client = new MongoClient(""); - -Create a client once for each process, and reuse it for all -operations. It is a common mistake to create a new client for each -request, which is very inefficient. - -There is no supported way to terminate a ``MongoClient`` in the driver. - -Why Does the Driver Throw a Timeout During Server Selection? ------------------------------------------------------------- - -Each driver operation requires that you choose a healthy server -satisfying the :manual:`server selection criteria -`. If you do not select an appropriate -server within the `server selection timeout <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.ServerSelectionTimeout.html>`__, the driver throws a -server selection timeout exception. The exception looks similar to the -following: - -.. code-block:: none - - A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. - Client view of cluster state is - { - ClusterId : "1", - Type : "Unknown", - State : "Disconnected", - Servers : - [{ - ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }", - EndPoint: "Unspecified/localhost:27017", - ReasonChanged: "Heartbeat", - State: "Disconnected", - ServerVersion: , - TopologyVersion: , - Type: "Unknown", - HeartbeatException: "" - }] - }. - -The error message consists of multiple parts: - -1. The server selection timeout (30000 ms). -#. The server selectors considered (``CompositeServerSelector`` - containing ``AreSessionsSupportedServerSelector``, - ``LatencyLimitingServerSelector``, and - ``OperationsCountServerSelector``). -#. The driver’s current view of the cluster topology. The list of - servers that the driver is aware of is a key part of this view. Each - server description contains an exhaustive description of its current - state including information about an endpoint, a server version, a - server type, and its current health state. If the server encounters issues in - reporting its health, ``HeartbeatException`` contains the exception from the - last failed heartbeat. Analyzing the ``HeartbeatException`` on each - cluster node can assist in diagnosing most server selection issues. - The following heartbeat exceptions are common: - - * ``No connection could be made because the target machine actively - refused it``: The driver cannot see this cluster node. This can be - because the cluster node has crashed, a firewall is preventing - network traffic from reaching the cluster node or port, or some other - network error is preventing traffic from being successfully routed to - the cluster node. - * ``Attempted to read past the end of the stream``: This error - happens when the driver cannot connect to the cluster nodes due to a - network error, misconfigured firewall, or other network issue. To - address this exception, ensure that all cluster nodes are reachable. - This error commonly occurs when the client machine’s IP address is - not configured in the Atlas IPs Access List, which can be found under - the :guilabel:`Network Access` tab for your Atlas Project. - * ``The remote certificate is invalid according to the validation - procedure``: This error typically indicates a TLS/SSL-related problem - such as an expired/invalid certificate or an untrusted root CA. You - can use tools like ``openssl s_client`` to debug TLS/SSL-related - certificate problems. - -.. _csharp-faq-linq-vs-builder: - -Should I Use LINQ, Builder Classes, or BSON Documents When Querying for Documents? ----------------------------------------------------------------------------------- - -If you're used to programming in {+language+}, consider using LINQ because of its similar feel -to programming in native {+language+}. If you have prior experience with other MongoDB drivers, -consider using builder classes because of their consistency with other drivers. BSON -documents offer the most flexibility and can translate more easily to other programming -languages, but are less idiomatic to {+language+} and do not check for type errors at -compile time. - -We encourage experimenting with each approach to determine the most suitable mechanism -for your purposes. To learn more about visualizing LINQ and builder class queries, see the -`{+analyzer+} `__. For assistance -in building BSON document queries, see the :compass:`MongoDB Compass <>` documentation. - -.. _csharp-faq-unsupported-expressions: - -Why are Certain LINQ or Builder Expressions Unsupported? --------------------------------------------------------- - -Each LINQ or Builder expression must be available in the Query API. This is not -always possible for the following reasons: - -1. You are attempting to use a {+lang-framework+} feature that does not have an - equivalent MongoDB representation. For example, {+lang-framework+} and MongoDB have - different semantics around collations. -#. The driver does not support a particular transformation from LINQ or - Builder expression into MQL (MongoDB Query Language). This may happen because the - provided query has no MQL translation or because a feature has not been - implemented yet in the driver. - -If you receive an ``Unsupported filter ...`` or ``Expression not -supported ...`` exception message, try the following -steps: - -1. Use the `{+analyzer+} - `__ to analyze your - expressions. -#. Try to simplify your query where possible. -#. Provide a query as a ``BsonDocument`` or JSON string. All driver - definition classes such as ``FilterDefinition``, - ``ProjectionDefinition``, and ``PipelineDefinition`` support implicit - conversion from ``BsonDocument`` or JSON string. For example, the - following filters are equivalent when used in a query or - aggregation: - -.. code-block:: csharp - - FilterDefinition typedFilter = Builders.Filter.Eq(e => e.A, 1); - FilterDefinition bsonFilter = new BsonDocument {{ "a", 1 }}; - FilterDefinition jsonFilter = "{ a : 1 }"; - -.. note:: - - If you use ``BsonDocument`` or JSON string, then `BsonClassMap - `__, - BSON serialization attributes, and serialization conventions are not - taken into account in the Query API. Field names must match the - names and casing as stored by the server. For example, when referencing - the ``_id`` field, you must refer to it using ``_id`` in - ``BsonDocument`` or JSON string definitions. Similarly, if a document - has a field ``FirstName`` annotated with ``[BsonElement("first_name")]``, you - must refer to it as ``first_name`` in ``BsonDocument`` or JSON string - definitions. - -You can combine the raw and typed forms in the same query, as the -following code demonstrates: - -.. code-block:: csharp - - FilterDefinition filter = Builders.Filter - .And(Builders.Filter - .Eq(e => e.A, 1), BsonDocument - .Parse("{ b : 2 }")); - -.. _csharp-faq-object-serializer: - -What Object Types Can Be Serialized? ------------------------------------- - -The ``ObjectSerializer`` allows serialization and deserialization only of types -that are considered safe. When you construct an ``ObjectSerializer``, -you can pass in a delegate of type ``Func``. This delegate -accepts an object type and returns a boolean value indicating whether the -type is safe for serialization. - -In most cases, you should pass in the ``ObjectSerializer.DefaultAllowedTypes()`` -delegate. This method returns true for a number of well-known -framework types that we have deemed safe. To serialize custom types, -create a boolean expression that evaluates to ``true`` for the -types you want to include. Then, add this expression to the end of the -delegate you pass to the ``ObjectSerializer`` constructor. - -In the following example, -the ``ObjectSerializer`` will serialize and deserialize any type that is allowed by -``ObjectSerializer.DefaultAllowedTypes()`` or whose full name begins with -``"MyNamespace"``: - -.. code-block:: csharp - - var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) - || type.FullName.StartsWith("MyNamespace")); - BsonSerializer.RegisterSerializer(objectSerializer); - -To allow anonymous types to be serialized, add the boolean expression -``type.FullName.StartsWith("<>f__AnonymousType"))`` to your delegate, -as shown in the following example: - -.. code-block:: csharp - - var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) - || type.FullName.StartsWith("<>f__AnonymousType")); - BsonSerializer.RegisterSerializer(objectSerializer); - -You should create and register your ``ObjectSerializer`` at the start of your program, -before doing anything else. - -What is the Difference Between the {+driver-short+} and the {+ef-provider-long+}? -------------------------------------------------------------------------------------------------- - -The {+driver-short+} is a library that exposes MongoDB functionality -directly and includes a LINQ provider with projections, group -operations, and flexible mapping. The driver includes features such as the -following: - -- Transactions -- Bulk operations -- LINQ queries -- Operations that directly modify the database -- Aggregation operations -- Custom mapping - -The `{+ef-provider-short+} `__ -allows you to use Microsoft's Entity Framework Core with -MongoDB in your {+lang-framework+} applications. The {+ef-provider-short+} supports -change tracking, entity-based LINQ operations, and modeling familiar to -Entity Framework Core users. The provider includes features such as the following: - -- Intelligent object tracking -- Entity-based LINQ operations -- Entity Framework modeling and mapping with the fluent API -- Automatic database updates through change tracking diff --git a/source/fundamentals.txt b/source/fundamentals.txt deleted file mode 100644 index 55498b5b..00000000 --- a/source/fundamentals.txt +++ /dev/null @@ -1,60 +0,0 @@ -.. _csharp-fundamentals: - -============ -Fundamentals -============ - -.. meta:: - :description: Learn how to use the MongoDB .NET/C# Driver to run commands on MongoDB. - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Connection - Databases & Collections - CRUD Operations - Operations with Builders - Atlas Search - Atlas Vector Search - Stable API - Authentication - Aggregation - LINQ - BSON Operations - Query - Serialization - Transactions - Indexes - Logging - Time Series Collections - In-Use Encryption - Search Geospatially - Store Large Files - Replica Set Operations - OData - Monitoring - -- :ref:`Connecting to MongoDB ` -- :ref:`csharp-db-coll` -- :ref:`csharp-crud` -- :ref:`csharp-builders` -- :ref:`csharp-atlas-search` -- :ref:`csharp-atlas-vector-search` -- :ref:`csharp-stable-api` -- :ref:`csharp-authentication-mechanisms` -- :ref:`csharp-aggregation` -- :ref:`csharp-linq` -- :ref:`csharp-bson` -- :ref:`csharp-specify-query` -- :ref:`csharp-serialization` -- :ref:`csharp-transactions` -- :ref:`csharp-indexes` -- :ref:`csharp-logging` -- :ref:`csharp-time-series` -- :ref:`Encrypt Fields ` -- :ref:`csharp-geo` -- :ref:`csharp-gridfs` -- :ref:`csharp-read-write-config` -- :ref:`csharp-odata` -- :ref:`csharp-monitoring` \ No newline at end of file diff --git a/source/fundamentals/aggregation.txt b/source/fundamentals/aggregation.txt deleted file mode 100644 index 879c0a8d..00000000 --- a/source/fundamentals/aggregation.txt +++ /dev/null @@ -1,222 +0,0 @@ -.. _csharp-aggregation: - -=========== -Aggregation -=========== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, transform, pipeline - :description: Learn to perform aggregation operations using the MongoDB .NET/C# Driver, including examples with LINQ, Builders, and BsonDocument approaches. - -.. 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 -**aggregation operations**. - -Aggregation operations process data in your MongoDB collections and -return computed results. The MongoDB Aggregation framework is modeled on the -concept of data processing pipelines. Documents enter a pipeline comprised of one or -more stages, and this pipeline transforms the documents into an aggregated result. - -Analogy -~~~~~~~ - -Aggregation operations function similarly to car factories with assembly -lines. The assembly lines have stations with specialized tools to -perform specific tasks. For example, when building a car, the assembly -line begins with the frame. Then, as the car frame moves through the -assembly line, each station assembles a separate part. The result is a -transformed final product, the finished car. - -The assembly line represents the *aggregation pipeline*, the individual -stations represent the *aggregation stages*, the specialized tools -represent the *expression operators*, and the finished product -represents the *aggregated result*. - -Compare Aggregation and Find Operations ---------------------------------------- - -The following table lists the different tasks you can perform with find -operations, compared to what you can achieve with aggregation -operations. The aggregation framework provides expanded functionality -that allows you to transform and manipulate your data. - -.. list-table:: - :header-rows: 1 - :widths: 50 50 - - * - Find Operations - - Aggregation Operations - - * - | Select *certain* documents to return - | Select *which* fields to return - | Sort the results - | Limit the results - | Count the results - - | Select *certain* documents to return - | Select *which* fields to return - | Sort the results - | Limit the results - | Count the results - | Group the results - | Rename fields - | Compute new fields - | Summarize data - | Connect and merge data sets - -Server Limitations ------------------- - -Consider the following :manual:`limitations ` when -performing aggregation operations: - -- Returned documents must not violate the :manual:`BSON document size limit ` - of 16 megabytes. - -- Pipeline stages have a memory limit of 100 megabytes by default. If required, you can exceed this limit by setting - the `AllowDiskUse <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AggregateOptions.AllowDiskUse.html#MongoDB_Driver_AggregateOptions_AllowDiskUse>`__ - property of the ``AggregateOptions`` object that you pass to the ``Aggregate()`` method. - -- The :manual:`$graphLookup ` stage has - a strict memory limit of 100 megabytes and ignores the ``AllowDiskUse`` property. - -Aggregation Example -------------------- - -To perform an aggregation, pass a list of aggregation stages to the -``IMongoCollection.Aggregate()`` method. - -.. note:: - - This example uses the ``sample_restaurants.restaurants`` collection - from the :atlas:`Atlas sample datasets `. To learn how to create a - free MongoDB Atlas cluster and load the sample datasets, see :ref:`csharp-quickstart`. - -The following code example produces a count of the number of bakeries in each borough -of New York City. To do so, it uses an aggregation pipeline that contains the following stages: - -- A :manual:`$match ` stage to filter for documents whose - ``cuisine`` field contains the value ``"Bakery"``. - -- A :manual:`$group ` stage to group the matching - documents by the ``borough`` field, accumulating a count of documents for each distinct value - of that field. - -The following sections implement this example by using LINQ, Builders, and BsonDocument -approaches to create and combine the aggregation stages used in the example pipeline. - -LINQ Approach -~~~~~~~~~~~~~ - -.. io-code-block:: - - .. input:: /includes/fundamentals/code-examples/LinqAggregation.cs - :language: csharp - :dedent: - :start-after: begin-aggregation - :end-before: end-aggregation - - .. output:: - :language: console - :visible: false - - { _id = Bronx, Count = 71 } - { _id = Brooklyn, Count = 173 } - { _id = Staten Island, Count = 20 } - { _id = Missing, Count = 2 } - { _id = Manhattan, Count = 221 } - { _id = Queens, Count = 204 } - -To learn more about using LINQ to construct aggregation pipelines, see the -:ref:`csharp-linq` guide. - -Builders Approach -~~~~~~~~~~~~~~~~~ - -.. io-code-block:: - - .. input:: /includes/fundamentals/code-examples/BuilderAggregation.cs - :language: csharp - :dedent: - :start-after: begin-aggregation - :end-before: end-aggregation - - .. output:: - :language: console - :visible: false - - { _id = Bronx, Count = 71 } - { _id = Brooklyn, Count = 173 } - { _id = Staten Island, Count = 20 } - { _id = Missing, Count = 2 } - { _id = Manhattan, Count = 221 } - { _id = Queens, Count = 204 } - -To learn more about using builders to construct aggregation pipelines, -see the :ref:`csharp-builders-aggregation` section of the Operations with Builders guide. - -BsonDocument Approach -~~~~~~~~~~~~~~~~~~~~~ - -.. io-code-block:: - - .. input:: /includes/fundamentals/code-examples/Aggregation.cs - :language: csharp - :dedent: - :start-after: begin-aggregation - :end-before: end-aggregation - - .. output:: - :language: console - :visible: false - - { "_id" : "Brooklyn", "count" : 173 } - { "_id" : "Manhattan", "count" : 221 } - { "_id" : "Bronx", "count" : 71 } - { "_id" : "Missing", "count" : 2 } - { "_id" : "Staten Island", "count" : 20 } - { "_id" : "Queens", "count" : 204 } - -Additional Information ----------------------- - -MongoDB Server Manual -~~~~~~~~~~~~~~~~~~~~~ - -To view a full list of expression operators, see -:manual:`Aggregation Operators `. - -To learn more about assembling an aggregation pipeline and view examples, see -:manual:`Aggregation Pipeline `. - -To learn more about creating pipeline stages, see -:manual:`Aggregation Stages `. - -To learn about explaining MongoDB aggregation operations, see -:manual:`Explain Results ` and -:manual:`Query Plans `. - -API Documentation -~~~~~~~~~~~~~~~~~ - -For more information about the aggregation operations discussed in this guide, see the -following API documentation: - -- `Aggregate() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.Aggregate.html>`__ -- `AggregateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AggregateOptions.html>`__ -- `Group() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineStageDefinitionBuilder.Group.html>`__ -- `Match() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineStageDefinitionBuilder.Match.html>`__ -- `Where() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.Where.html>`__ -- `GroupBy() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.GroupBy.html>`__ -- `Select() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.Select.html>`__ diff --git a/source/fundamentals/atlas-vector-search.txt b/source/fundamentals/atlas-vector-search.txt deleted file mode 100644 index f99da565..00000000 --- a/source/fundamentals/atlas-vector-search.txt +++ /dev/null @@ -1,201 +0,0 @@ -.. _csharp-atlas-vector-search: - -=================== -{+vector-search+} -=================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: .NET, search, semantic, AI, RAG - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -You can use {+vector-search+} to perform vector search on your data stored in -Atlas. Vector search allows you to query your data based on semantic meaning -rather than just keyword matches, which helps you retrieve more relevant search -results. It enables your AI-powered applications to support use cases such as -semantic search, hybrid search, and generative search, including -Retrieval-Augmented Generation (RAG). - -By using Atlas as a vector database, you can seamlessly index vector data along -with your other data in Atlas. This allows you to filter on fields in your -collection and perform vector search queries against vector data. You can also -combine vector search with full-text search queries to return the most relevant -results for your use case. You can integrate {+vector-search+} with popular AI -frameworks and services to easily implement vector search in your applications. - -To learn more about {+vector-search+}, see the :atlas:`{+vector-search+} -` guide in the MongoDB Atlas -documentation. - -.. _csharp-supported-vector-types: - -Supported Vector Embedding Types --------------------------------- - -:atlas:`Vector embeddings -` -are vectors you use to represent your data. These embeddings -capture meaningful relationships in your data and enable tasks like semantic -search and retrieval. - -The {+driver-short+} supports vector embeddings of several types. The following -sections describe the supported vector embedding types. - -.. _csharp-vector-array-representation: - -Array Representations -~~~~~~~~~~~~~~~~~~~~~ - -The {+driver-short+} supports the following representations of the array -type in vector embeddings: - -- ``BsonArray`` -- ``Memory`` -- ``ReadOnlyMemory`` -- ``float[]`` and ``double[]`` - -The following example shows a class with properties of the preceding types: - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs - :language: csharp - :start-after: start-bson-arrays - :end-before: end-bson-arrays - -.. tip:: - - To learn more about using the ``Memory`` and ``ReadOnlyMemory`` - types, see the :ref:`csharp-array-serialization` section of the - Serialization guide. - -.. _csharp-binary-vector-representation: - -Binary Vector Representations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The {+driver-short+} supports the following binary vector representations in -vector embeddings: - -- ``BinaryVectorFloat32`` (not supported on big-endian architectures) -- ``BinaryVectorInt8`` -- ``BinaryVectorPackedBit`` -- ``Memory``, ``Memory``, ``Memory`` -- ``ReadOnlyMemory``, ``ReadOnlyMemory``, ``ReadOnlyMemory`` -- ``float[]``, ``byte[]``, ``sbyte[]`` - -.. note:: - - You must use the ``BinaryVector`` attribute when specifying binary vector - representations of the ``Memory``, ``ReadOnlyMemory``, or array - types. - -The following example shows a class with properties of the preceding types: - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs - :language: csharp - :start-after: start-binary-vectors - :end-before: end-binary-vectors - -Binary Vector Data Serialization -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can serialize ``Int8`` binary vector typed data as ``byte`` or ``sbyte``. -You can also serialize ``Float32`` binary vector typed data as ``float``. The -following example serializes ``Int8`` and ``Float32`` binary vector data: - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs - :language: csharp - :start-after: start-binary-int-float-serialize - :end-before: end-binary-int-float-serialize - -You can deserialize ``PackedBit`` vector data to a :ref:`binary vector -represented ` ``byte`` data type only if the -vector data has a padding value of ``0``. If the vector data has a padding value not -equal to ``0``, you can deserialize it only to a ``BsonVectorPackedBit``. - -Vector Search Query Example ---------------------------- - -You can perform a vector search query by calling the ``VectorSearch()`` method -in an :ref:`aggregation pipeline `. To perform a vector -search on a collection, you must first have a collection with a field that contains -vector data and a vector search index that covers that field. - -.. tip:: - - To learn more about configuring a collection for vector search, see the :atlas:`{+vector-search+} - ` guide in the MongoDB Atlas - documentation. - -You can convert ``BinaryVectorFloat32``, ``BinaryVectorInt8``, and -``BinaryVectorPackedBit`` data to the ``BsonBinaryData`` type to use in a vector -search query by using the ``ToQueryVector()`` method. The following example -converts ``BinaryVectorInt8`` into a ``BsonBinaryData`` object: - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs - :language: csharp - :start-after: start-to-query-vector - :end-before: end-to-query-vector - -You can specify your :ref:`array-represented -` vector data as an instance of the -``QueryVector`` class to use in a vector search query. The following example -creates an array of ``ReadOnlyMemory`` values as a ``QueryVector`` object -to use in a vector search query: - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs - :language: csharp - :start-after: start-array-query-vector - :end-before: end-array-query-vector - -Example -~~~~~~~ - -This example performs the following steps to run an {+vector-search+} query on a collection that -contains vector data and a vector search index on the ``PlotEmbedding`` field: - -1. Creates an array that contains the :ref:`array-represented - ` vector data to search for -#. Specifies a ``VectorSearchOptions`` object that contains the name of the index - and the number of nearest neighbors to use during the search -#. Creates an aggregation pipeline that uses the ``VectorSearch()`` stage to - perform the vector search query and a ``Project()`` stage to filter the - results -#. Prints the results of the query - -.. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs - :language: csharp - :start-after: start-search-example - :end-before: end-search-example - :emphasize-lines: 11 - -Additional Information ----------------------- - -To learn more about {+vector-search+}, see the :atlas:`{+vector-search+} -` guide in the MongoDB Atlas -documentation. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about any of the functions or types discussed in this -guide, see the following API Documentation: - -- `BinaryVectorFloat32 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorFloat32.html>`__ -- `BinaryVectorInt8 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorInt8.html>`__ -- `BinaryVectorFloat32 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorPackedBit.html>`__ -- `ToQueryVector() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BinaryVectorDriverExtensions.ToQueryVector.html>`__ -- `VectorSearch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AggregateFluentBase-1.VectorSearch.html>`__ -- `Aggregate() - <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Aggregate.html>`__ diff --git a/source/fundamentals/connection.txt b/source/fundamentals/connection.txt deleted file mode 100644 index 63ad50e6..00000000 --- a/source/fundamentals/connection.txt +++ /dev/null @@ -1,34 +0,0 @@ -.. _csharp-connection: - -========== -Connection -========== - -.. meta:: - :description: Learn to connect your application to MongoDB using the .NET/C# Driver, including connection options and enabling TLS. - -.. default-domain:: mongodb - -.. toctree:: - - Connection Guide - Connection Options - Configure TLS - Network Compression - Connect with AWS Lambda - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -In this section, you'll learn how to use the {+driver-short+} to connect your application to a MongoDB deployment. Click a link in the following list to jump to a topic: - -- :ref:`How to Connect to MongoDB ` -- :ref:`Connection Options ` -- :ref:`Enable TLS on a Connection ` -- :atlas:`Connect to MongoDB Atlas from AWS Lambda ` \ No newline at end of file diff --git a/source/fundamentals/connection/connect.txt b/source/fundamentals/connection/connect.txt deleted file mode 100644 index 68d5def2..00000000 --- a/source/fundamentals/connection/connect.txt +++ /dev/null @@ -1,161 +0,0 @@ -.. _csharp-connect-to-mongodb: - -================ -Connection Guide -================ - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: connection string, URI, server, Atlas, settings - :description: Connect to a MongoDB instance or replica set using the .NET/C# Driver by configuring a connection URI or `MongoClientSettings` for various deployment types. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -This guide shows you how to connect to a MongoDB instance or replica set -deployment using the {+driver-short+}. - -.. _csharp_connection_uri: - -Connection URI --------------- - -A **connection URI**, also known as a *connection string*, tells the driver how to connect to a MongoDB deployment and how to behave while connected. - -A standard connection string includes the following pieces: - -.. list-table:: - :widths: 20 80 - :header-rows: 1 - - * - Piece - - Description - - * - ``mongodb://`` - - - Required. A prefix that identifies this as a string in the - standard connection format. - - * - ``username:password@`` - - - Optional. Authentication credentials. If you include these, the client will authenticate the user against the database specified in ``authSource``. - - * - ``host[:port]`` - - - Required. The host and optional port number where MongoDB is running. If you don't include the port number, the driver will use the default port, ``27017``. - - * - ``/defaultauthdb`` - - - Optional. The authentication database to use if the - connection string includes ``username:password@`` - authentication credentials but not the ``authSource`` option. If you don't include - this piece, the client will authenticate the user against the ``admin`` database. - - * - ``?`` - - - Optional. A query string that specifies connection-specific - options as ``=`` pairs. See - :ref:`csharp-connection-options` for a full description of - these options. - -To use a connection URI, pass it as a string to the ``MongoClient`` constructor. In the -following example, the driver uses a sample connection URI to connect to a MongoDB -instance on port ``27017`` of ``localhost``: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/LocalConnection.cs - :language: csharp - :start-after: // start local connection - :end-before: // end local connection - -.. tip:: Reuse Your Client - - Because each ``MongoClient`` represents a pool of connections to the - database, most applications require only a single instance of - ``MongoClient``, even across multiple requests. To learn more about - how connection pools work in the driver, see the :ref:`FAQ page - `. - -See :manual:`the MongoDB Manual ` for more information about creating a connection string. - -MongoClientSettings -------------------- - -You can use a ``MongoClientSettings`` object to configure the connection in code -rather than in a connection URI. To use a ``MongoClientSettings`` object, create an -instance of the class and pass it as an argument to the ``MongoClient`` constructor. - -In the following example, the driver uses a ``MongoClientSettings`` object to connect to a -MongoDB instance on port ``27017`` of ``localhost``: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/MongoClientSettings.cs - :language: csharp - :dedent: - :start-after: // start mongo client settings - :end-before: // end mongo client settings - -Other Connection Targets ------------------------- - -Connect to Atlas -~~~~~~~~~~~~~~~~ - -To connect to a MongoDB deployment on Atlas, create a client. You can -create a client that uses your connection string and other -client options by passing a ``MongoClientSettings`` object to the ``MongoClient`` -constructor. - -To specify your connection URI, pass it to the ``FromConnectionString()`` -method, which returns a new ``MongoClientSettings`` instance. To specify any other -client options, set the relevant fields of the ``MongoClientSettings`` object. - -You can set the {+stable-api+} version as a client option to avoid -breaking changes when you upgrade to a new server version. To -learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page -`. - -The following code shows how you can specify the connection string and -the {+stable-api+} client option when connecting to a MongoDB -deployment and verify that the connection is successful: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/AtlasConnection.cs - :language: csharp - :start-after: // start atlas connection - :end-before: // end atlas connection - -.. tip:: - - Follow the :atlas:`Atlas driver connection guide ` - to retrieve your connection string. - -Connect to a Replica Set -~~~~~~~~~~~~~~~~~~~~~~~~ - -To connect to a replica set deployment, specify the hostnames (or IP addresses) and -port numbers of the members of the replica set. - -If you aren't able to provide a full list of hosts in the replica set, you can -specify one or more of the hosts in the replica set and instruct the driver to -perform automatic discovery in one of the following ways: - -- Specify the name of the replica set as the value of the ``replicaSet`` parameter. -- Specify ``false`` as the value of the ``directConnection`` parameter. -- Specify more than one host in the replica set. - -In the following example, the driver uses a sample connection URI to connect to the -MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different -hosts, including ``sample.host1``: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs - :language: csharp - :start-after: // start replica set connection - :end-before: // end replica set connection - -.. note:: Replica Set in Docker - - .. sharedinclude:: dbx/docker-replica-set.rst \ No newline at end of file diff --git a/source/fundamentals/connection/connection-options.txt b/source/fundamentals/connection/connection-options.txt deleted file mode 100644 index e94b7ab7..00000000 --- a/source/fundamentals/connection/connection-options.txt +++ /dev/null @@ -1,472 +0,0 @@ -.. _csharp-connection-options: - -================== -Connection Options -================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: connection string, URI, server, Atlas, settings, configure - :description: Explore MongoDB connection and authentication options in the .NET/C# Driver using connection URI or `MongoClientSettings` for flexible configuration. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -This section describes the MongoDB connection and authentication options -available in the {+driver-short+}. You can configure your connection using either -the connection URI or a ``MongoClientSettings`` object. - -.. _csharp-connection-uri: - ------------------------- -Using the Connection URI ------------------------- - -If you pass a connection URI to the ``MongoClient`` constructor, you can include -connection options in the string as ``=`` pairs. In the following example, -the connection URI contains the ``connectTimeoutMS`` option with a value of ``60000`` -and the ``tls`` option with a value of ``true``: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/LocalConnectionConfig.cs - :language: csharp - :dedent: - :start-after: // start local connection config - :end-before: // end local connection config - -.. _csharp-mongo-client-settings: - ------------------------------ -Using ``MongoClientSettings`` ------------------------------ - -You can use a ``MongoClientSettings`` object to configure connection settings in code -rather than in a connection URI. Configuring the connection this way makes it easier to -change settings at runtime, helps you catch errors during compilation, and provides -more configuration options than the connection URI. - -To use a ``MongoClientSettings`` object, create an instance of the class, set -its properties, and pass it as an argument to the ``MongoClient`` constructor: - -.. literalinclude:: /includes/fundamentals/code-examples/connection/MongoClientSettingsConfig.cs - :language: csharp - :dedent: - :start-after: // start mongo client settings config - :end-before: // end mongo client settings config - -Connection Options ------------------- - -The following table lists each connection option available in the -``MongoClientSettings`` class and, if possible, how to achieve the same result in -the connection string. If a ``MongoClientSettings`` property maps to more than one -option in the connection string, the **Connection URI Example** shows all -relevant options. - -.. note:: - - If you're using a query parameter for a time duration, the value must be in - milliseconds. For example, to specify 60 seconds, use the value ``60000``. If you're - using a ``MongoClientSettings`` object for a time duration, use the appropriate - ``TimeSpan`` value. - -.. list-table:: - :header-rows: 1 - :widths: 30 70 - - * - **MongoClientSettings** Property - - Description - - * - **AllowInsecureTls** - - | Specifies whether to relax TLS constraints as much as possible. This can include - | allowing invalid certificates or hostname mismatches. - | - | If this property is set to ``true`` and ``SslSettings.CheckCertificateRevocation`` - | is set to ``false``, the {+driver-short+} will throw an exception. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: ``tlsInsecure=true`` - - * - **ApplicationName** - - | The app name the driver passes to the server in the client metadata as part of - | the connection handshake. The server prints this value to the MongoDB logs once - | the connection is established. The value is also recorded in the slow query logs - | and profile collections. - | - | **Data Type**: {+string-data-type+} - | **Default**: ``null`` - | **Connection URI Example**: ``appName=yourApp`` - - * - **AutoEncryptionOptions** - - | Settings for automatic client-side encryption. - | - | **Data Type**: `AutoEncryptionOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.AutoEncryptionOptions.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: {+not-available+} - - * - **ClusterConfigurator** - - | Low-level configuration options for sockets, TLS, cluster, and others. - | - | **Data Type**: Action<`ClusterBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ClusterBuilder.html>`__> - | **Default**: ``null`` - | **Connection URI Example**: {+not-available+} - - * - **Compressors** - - | The preferred compression types, in order, for wire-protocol messages sent to - | or received from the server. The driver uses the first of these compression types - | that the server supports. - | - | **Data Type**: `CompressorConfiguration <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.CompressorConfiguration.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: ``compressors=snappy,zstd`` - - * - **ConnectTimeout** - - | The length of time the driver tries to establish a single TCP socket connection - | to the server before timing out. - | - | **DataType**: ``TimeSpan`` - | **Default**: 30 seconds - | **Connection URI Example**: ``connectTimeoutMS=0`` - - * - **Credential** - - | Settings for how the driver authenticates to the server. This includes - | authentication credentials, mechanism, source, and other settings. - | - | If you don't specify an authentication mechanism, the driver uses either - | ``SCRAM-SHA-1`` or ``SCRAM-SHA-256``, depending on the server version. See - | :ref:`authentication mechanisms ` for available - | authentication mechanisms. - | - | **Data Type**: `MongoCredential <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoCredential.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: - - .. code-block:: none - :copyable: false - - mongodb://user1:password1&authMechanism=GSSAPI - &authMechanismProperties=SERVICE_NAME:other,REALM:otherrealm - &authSource=$external - - * - **DirectConnection** - - | Specifies whether to force dispatch **all** operations to the host. - | - | If you specify this option, the driver doesn't accept the - | :manual:`DNS seed list connection format. ` - | You must use the :manual:`standard connection URI format ` - | instead. - | - | This property must be set to ``false`` if you specify more than one - | host name. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: ``directConnection=true`` - - * - **HeartbeatInterval** - - | The interval between regular server-monitoring checks. Must be greater than or - | equal to 500 milliseconds. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 10 seconds - | **Connection URI Example**: ``heartbeatFrequencyMS=5000`` - - * - **HeartbeatTimeout** - - | The length of time a monitoring socket can be idle before timing out. - | - | **Data Type**: ``TimeSpan`` - | **Default**: Same value as ``ConnectTimeout`` - | **Connection URI Example**: ``heartbeatTimeoutMS=5000`` - - * - **IPv6** - - | Specifies whether the host address is in IPv6 format. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: ``ipv6=true`` - - * - **IsFrozen** - - | Indicates whether the settings have been frozen. Frozen settings can't be changed. - | This option is read-only. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: {+not-available+} - - * - **LoadBalanced** - - | Specifies whether the driver is connecting to a load balancer. You can set this - | property to ``true`` only if: - - - You specify just one host name. - - You're not connecting to a replica set. - - You're not using the ``SrvMaxHosts`` property. - - You're not using the ``DirectConnection`` property. - - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: ``loadBalanced=true`` - - * - **LocalThreshold** - - | The latency window for server eligibility. If a server's round trip takes longer - | than the fastest server's round-trip time plus this value, the server isn't - | eligible for selection. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 15 milliseconds - | **Connection URI Example**: ``localThresholdMS=0`` - - * - **LoggingSettings** - - | The settings used for :ref:`logging. ` - | - | **Data Type**: `LoggingSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.LoggingSettings.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: {+not-available+} - - * - **MaxConnecting** - - | The greatest number of connections a driver's connection pool may be - | establishing concurrently. - | - | **Data Type**: {+int-data-type+} - | **Default**: ``2`` - | **Connection URI Example**: ``maxConnecting=3`` - - * - **MaxConnectionIdleTime** - - | The length of time a connection can be idle before the driver closes it. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 10 minutes - | **Connection URI Example**: ``maxIdleTimeMS=300000`` - - * - **MaxConnectionLifeTime** - - | The length of time a connection can be pooled before expiring. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 30 minutes - | **Connection URI Example**: ``maxLifetimeMS=50000`` - - * - **MaxConnectionPoolSize** - - | The greatest number of clients or connections the driver can create in its - | connection pool. This count includes connections in use. - | - | **Data Type**: {+int-data-type+} - | **Default**: ``100`` - | **Connection URI Example**: ``maxPoolSize=150`` - - * - **MinConnectionPoolSize** - - | The number of connections the driver should create and keep in the connection - | pool even when no operations are occurring. This count includes connections - | in use. - | - | **Data Type**: {+int-data-type+} - | **Default**: ``0`` - | **Connection URI Example**: ``minPoolSize=1`` - - * - **ReadConcern** - - | The client's default read concern. - | See :ref:`read concern ` for more information. - | - | **Data Type**: `ReadConcern <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadConcern.html>`__ - | **Default**: ``ReadConcern.Default`` - | **Connection URI Example**: ``readConcernLevel=local`` - - * - **ReadEncoding** - - | The UTF-8 encoding to use for string deserialization. - | Strict encoding will throw an exception when an invalid UTF-8 byte sequence - | is encountered. - | - | **Data Type**: ``UTF8Encoding`` - | **Default**: Strict encoding - | **Connection URI Example**: {+not-available+} - - * - **ReadPreference** - - | The client's default read-preference settings. ``MaxStaleness`` represents the - | longest replication lag, in wall-clock time, that a secondary can experience and - | still be eligible for server selection. Specifying ``-1`` means no maximum. - | See :ref:`read preference ` for more information. - | - | **Data Type**: `ReadPreference <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReadPreference.html>`__ - | **Default**: ``ReadPreference.Primary`` - | **Connection URI Example**: - - .. code-block:: none - :copyable: false - - readPreference=primaryPreferred - &maxStalenessSeconds=90 - &readPreferenceTags=dc:ny,rack:1 - - | You can include the ``readPreferenceTags`` parameter in the connection URI more - than once. If you do, the client treats each instance as a separate tag set. - The order of the tags in the URI determines the order for read preference. You can - use this parameter only if the read-preference mode is not ``primary``. - - * - **ReplicaSetName** - - | The name of the replica set to connect to. - | - | **Data Type**: {+string-data-type+} - | **Default**: ``null`` - | **Connection URI Example**: ``replicaSet=yourReplicaSet`` - - * - **RetryReads** - - | Enables retryable reads. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``true`` - | **Connection URI Example**: ``retryReads=false`` - - * - **RetryWrites** - - | Enables retryable writes. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``true`` - | **Connection URI Example**: ``retryWrites=false`` - - * - **Scheme** - - | Specifies whether to use the standard connection string format (``MongoDB``) - | or the DNS seed list format (``MongoDBPlusSrv``). - | See :manual:`the MongoDB Manual` for more - | information about connection string formats. - | - | If the ``DirectConnection`` property is set to ``true`` and you - | try to use the DNS seed list format, the {+driver-short+} will throw an - | exception. - | - | **Data Type**: `ConnectionStringScheme <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ConnectionStringScheme.html>`__ - | **Default**: ``ConnectionStringScheme.MongoDB`` - | **Connection URI Example**: ``mongodb+srv://`` - - * - **Server** - - | The host and port number where MongoDB is running. - | - | **Data Type**: `MongoServerAddress <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoServerAddress.html>`__ - | **Default**: ``localhost:27017`` - | **Connection URI Example**: ``mongodb://sample.host:27017`` - - * - **ServerApi** - - | Allows opting into Stable API versioning. See - | :manual:`the MongoDB Manual` for more information about - | Stable API versioning. - | - | **Data Type**: `ServerApi <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ServerApi.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: {+not-available+} - - * - **ServerMonitoringMode** - - | Specifies the server monitoring protocol to use. When - | this option is set to ``Auto``, the monitoring mode is determined - | by the environment in which the driver is running. The driver - | uses polling mode in function-as-a-service (FaaS) environments, - | such as AWS Lambda, and the streaming mode in other environments. - | - | **Data Type**: `ServerMonitoringMode <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Servers.ServerMonitoringMode.html>`__ - | **Default**: ``Auto`` - | **Connection URI Example**: ``serverMonitoringMode=poll`` - - * - **Servers** - - | The cluster members where MongoDB is running. - | - | **Data Type**: IEnumerable<`MongoServerAddress <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoServerAddress.html>`__> - | **Default**: ``localhost:27017`` - | **Connection URI Example**: ``mongodb://sample.host1:27017,sample.host2:27017`` - - * - **ServerSelectionTimeout** - - | The length of time the driver tries to select a server before timing out. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 30 seconds - | **Connection URI Example**: ``serverSelectionTimeoutMS=15000`` - - * - **SocketTimeout** - - | The length of time the driver tries to send or receive on a socket before - | timing out. - | - | **Data Type**: ``TimeSpan`` - | **Default**: OS default - | **Connection URI Example**: ``socketTimeoutMS=0`` - - * - **SrvMaxHosts** - - | The greatest number of SRV results to randomly select when initially populating - | the seedlist or, during SRV polling, adding new hosts to the topology. - | - | You can use this property only if the connection-string scheme is set - | to ``ConnectionStringScheme.MongoDBPlusSrv``. You cannot use it when connecting - | to a replica set. - | - | **Data Type**: {+int-data-type+} - | **Default**: ``0`` - | **Connection URI Example**: ``srvMaxHosts=3`` - - * - **SrvServiceName** - - | The service name of the `SRV resource records `__ - | that the driver retrieves to construct your seedlist. This - | property overrides the default service name for SRV lookup in - | discovery and polling. - | - | You can use this property only if the connection-string scheme is set - | to ``ConnectionStringScheme.MongoDBPlusSrv``. You cannot use it when connecting - | to a replica set. - | - | **Data Type**: {+string-data-type+} - | **Default**: ``"mongodb"`` - | **Connection URI Example**: ``srvServiceName="customname"`` - - * - **SslSettings** - - | TLS/SSL options, including client certificates, revocation handling, and - | enabled and disabled TLS/SSL protocols. - | - | If ``SslSettings.CheckCertificateRevocation`` is set to ``false`` and - | ``AllowInsecureTls`` is set to ``true``, the {+driver-short+} will throw - | an exception. - | - | **Data Type**: `SslSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.SslSettings.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: ``tlsDisableCertificateRevocationCheck=false`` - - * - **TranslationOptions** - - | Specifies options, such as the {+mdb-server+} version, for translating LINQ - | queries to the Query API. - | - | **Data Type**: `ExpressionTranslationOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ExpressionTranslationOptions.html>`__ - | **Default**: ``null`` - | **Connection URI Example**: {+not-available+} - - * - **UseTls** - - | Specifies whether to require TLS for connections to the server. If you use - | a scheme of ``"mongodb+srv"`` or specify other TLS options, - | this option defaults to ``true``. - | - | **Data Type**: {+bool-data-type+} - | **Default**: ``false`` - | **Connection URI Example**: ``tls=true`` - - * - **WaitQueueTimeout** - - | The length of time the driver tries to check out a connection from a - | server's connection pool before timing out. - | - | **Data Type**: ``TimeSpan`` - | **Default**: 2 minutes - | **Connection URI Example**: ``waitQueueTimeoutMS=0`` - - * - **WriteConcern** - - | The default write-concern settings, including write timeout and - | journaling, for the client. - | See :ref:`write concern ` for more information. - | - | **Data Type**: `WriteConcern <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.WriteConcern.html>`__ - | **Default**: ``WriteConcern.Acknowledged`` - | **Connection URI Example**: ``w=majority&wTimeoutMS=0&journal=true`` - - * - **WriteEncoding** - - | Specifies whether UTF-8 string serialization is strict or lenient. With strict - | encoding, the driver will throw an exception when it encounters an invalid - | UTF-8 byte sequence. - | - | **Data Type**: ``UTF8Encoding`` - | **Default**: Strict encoding - | **Connection URI Example**: {+not-available+} diff --git a/source/fundamentals/crud.txt b/source/fundamentals/crud.txt deleted file mode 100644 index f0f2c8da..00000000 --- a/source/fundamentals/crud.txt +++ /dev/null @@ -1,19 +0,0 @@ -.. _csharp-crud: - -=============== -CRUD Operations -=============== - -.. meta:: - :description: Learn how to run create, read, update, delete (CRUD) MongoDB operations by using the {+driver-long+}. - -.. toctree:: - :caption: CRUD Operations - - Write - Read - Tutorial: Create a RESTful API - -- :ref:`csharp-crud-read-operations` -- :ref:`csharp-crud-write-operations` -- :ref:`csharp-crud-restful-api-tutorial` \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations.txt b/source/fundamentals/crud/read-operations.txt deleted file mode 100644 index 6938a56a..00000000 --- a/source/fundamentals/crud/read-operations.txt +++ /dev/null @@ -1,25 +0,0 @@ -.. _csharp-crud-read-operations: - -=============== -Read Operations -=============== - -.. meta:: - :description: Learn about the commands for running MongoDB read operations by using the {+driver-long+}. - -.. toctree:: - :caption: Read Operations - - Retrieve Data - Specify Fields to Return - Count Documents - List Distinct Values - Monitor Data Changes - Specify Query Results - -- :ref:`csharp-retrieve` -- :ref:`csharp-project` -- :ref:`csharp-count-documents` -- :ref:`csharp-distinct` -- :ref:`csharp-change-streams` -- :ref:`csharp-specify-documents-to-return` diff --git a/source/fundamentals/crud/read-operations/project.txt b/source/fundamentals/crud/read-operations/project.txt deleted file mode 100644 index fb64294e..00000000 --- a/source/fundamentals/crud/read-operations/project.txt +++ /dev/null @@ -1,145 +0,0 @@ -.. _csharp-project: - -======================== -Specify Fields To Return -======================== - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: read, filter, project, select - -Overview --------- - -In this guide, you can learn how to specify which fields to return from a read -operation by using a **projection**. A projection is a document that specifies -which fields MongoDB returns from a query. - -Sample Data -~~~~~~~~~~~ - -The examples in this guide use the ``sample_restaurants.restaurants`` collection -from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. - -Projection Types ----------------- - -You can use a projection to specify which fields to include in a return -document, or to specify which fields to exclude. - -When specifying certain fields to include in a projection, all other fields are implicitly -excluded (except the ``_id`` field, which is included by default). You cannot combine -inclusion and exclusion statements in a single projection, unless you are excluding the -``_id`` field. - -To remove the ``_id`` field from the returned document, you must -:ref:`explicitly exclude it `. - -Specify Fields to Include -~~~~~~~~~~~~~~~~~~~~~~~~~ - -To specify the fields to include from the result, chain the ``Project()`` method -to the ``Find()`` method. When calling the ``Project()`` method, you must pass in the -projection definition as a parameter. You can construct a projection definition by using -the ``Builders.Projection.Include()`` method and passing in the field name to include -as a parameter. This method can be chained to include multiple fields in the projection. - -The following example uses the ``Find()`` method to find all restaurants in which the ``name`` -field value is ``"Emerald Pub"``. Then, the code calls the ``Project()`` -method to instruct the find operation to include the ``name`` and ``cuisine`` fields -in the result: - -.. io-code-block:: - :copyable: true - - .. input:: /includes/fundamentals/code-examples/Project.cs - :start-after: start-project-include - :end-before: end-project-include - :language: csharp - :dedent: - - .. output:: - :visible: false - - { "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" } - { "_id" : ObjectId("..."), "cuisine" : "American", "name" : "Emerald Pub" } - -.. _csharp-project-exclude-id: - -Exclude the ``_id`` Field -~~~~~~~~~~~~~~~~~~~~~~~~~ - -When specifying fields to include, you can also exclude the ``_id`` field from -the returned document. - -The following example runs the same query as the preceding example, but -excludes the ``_id`` field from the projection: - -.. io-code-block:: - :copyable: true - - .. input:: /includes/fundamentals/code-examples/Project.cs - :start-after: start-project-include-without-id - :end-before: end-project-include-without-id - :language: csharp - :dedent: - - .. output:: - :visible: false - - { "cuisine" : "American", "name" : "Emerald Pub" } - { "cuisine" : "American", "name" : "Emerald Pub" } - -Specify Fields to Exclude -~~~~~~~~~~~~~~~~~~~~~~~~~ - -To specify the fields to exclude from the result, chain the ``Project()`` method -to the ``Find()`` method. You can exclude fields in your projection by using -the ``Builders.Projection.Exclude()`` method and passing in the field name to exclude -as a parameter. This method can be chained to exclude multiple fields in the projection. - -The following example uses the ``Find()`` method to find all restaurants in which the ``name`` -field value is ``"Emerald Pub"``. It then uses a projection to exclude the ``cuisine`` -field from the returned documents: - -.. io-code-block:: - :copyable: true - - .. input:: /includes/fundamentals/code-examples/Project.cs - :start-after: start-project-exclude - :end-before: end-project-exclude - :language: csharp - :dedent: - - .. output:: - :visible: false - - { "_id" : ObjectId("..."), "address" : { "building" : "308", "coord" : [-74.008493599999994, 40.725807199999998], "street" : "Spring Street", "zipcode" : "10013" }, "borough" : "Manhattan", "grades" : [{ "date" : ISODate("2014-02-24T00:00:00Z"), "grade" : "A", "score" : 5 }, { "date" : ISODate("2013-08-26T00:00:00Z"), "grade" : "A", "score" : 13 }, { "date" : ISODate("2013-03-04T00:00:00Z"), "grade" : "A", "score" : 12 }, { "date" : ISODate("2012-06-25T00:00:00Z"), "grade" : "A", "score" : 10 }, { "date" : ISODate("2011-12-23T00:00:00Z"), "grade" : "A", "score" : 10 }, { "date" : ISODate("2011-07-26T00:00:00Z"), "grade" : "C", "score" : 32 }], "name" : "Emerald Pub", "restaurant_id" : "40367329" } - { "_id" : ObjectId("..."), "address" : { "building" : "18301", "coord" : [-73.791184999999999, 40.740119999999997], "street" : "Horace Harding Expressway", "zipcode" : "11365" }, "borough" : "Queens", "grades" : [{ "date" : ISODate("2014-05-07T00:00:00Z"), "grade" : "A", "score" : 12 }, { "date" : ISODate("2013-04-30T00:00:00Z"), "grade" : "A", "score" : 9 }, { "date" : ISODate("2012-03-01T00:00:00Z"), "grade" : "A", "score" : 13 }], "name" : "Emerald Pub", "restaurant_id" : "40668598" } - -Additional Information ----------------------- - -To learn more about projections, see the :manual:`Project Fields guide -` in the {+mdb-server+} manual. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about any of the functions or types discussed in this -guide, see the following API Documentation: - -- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`_ -- `Projection <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Builders-1.Projection.html>`_ -- `Include() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Include.html>`_ -- `Exclude() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.Exclude.html>`_ \ No newline at end of file diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt deleted file mode 100644 index 4543bd96..00000000 --- a/source/fundamentals/crud/write-operations.txt +++ /dev/null @@ -1,25 +0,0 @@ -.. _csharp-crud-write-operations: - -================ -Write Operations -================ - -.. meta:: - :description: Learn about the commands for running MongoDB write operations by using the {+driver-long+}. - -.. toctree:: - :caption: Write Operations - - Insert - Update One - Update Many - Replace - Delete - Bulk Write - -- :ref:`csharp-insert-guide` -- :ref:`csharp-update-one` -- :ref:`csharp-update-many` -- :ref:`csharp-replace-documents` -- :ref:`csharp-delete-guide` -- :ref:`csharp-bulk-write` diff --git a/source/fundamentals/specify-query.txt b/source/fundamentals/specify-query.txt deleted file mode 100644 index fbb2d4a6..00000000 --- a/source/fundamentals/specify-query.txt +++ /dev/null @@ -1,363 +0,0 @@ -.. _csharp-specify-query: - -=============== -Specify a Query -=============== - -.. meta:: - :description: Learn how to specify queries using the MongoDB .NET/C# Driver, including creating query filters and using comparison, logical, array, element, and evaluation operators. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Overview --------- - -In this guide, you can learn how to specify a query using the {+driver-long+}. - -You can narrow the set of matched documents returned by your query by creating a -**query filter**. A query filter is an expression that specifies the documents you -want to match in a read, update, or delete operation. - -.. note:: Using LINQ - - This guide shows how to specify queries using query filters. You can also - specify queries using LINQ. To learn more about using LINQ, see - :ref:`csharp-linq`. - -The examples in this guide use the following documents in a collection called -``guitars``: - -.. code-block:: json - - { "_id": 1, "make": "Fender", "models": ["Stratocaster", "Telecaster"], "establishedYear": 1946, "rating": 9 } - { "_id": 2, "make": "Gibson", "models": ["Les Paul", "SG", "Explorer"], "establishedYear": 1902, "rating": 8 } - { "_id": 3, "make": "PRS", "models": ["Silver Sky", "SE", "Custom"], "establishedYear": 1985, "rating": 9 } - { "_id": 4, "make": "Kiesel", "models": ["Ares", "Vader", "Solo"], "establishedYear": 2015 } - { "_id": 5, "make": "Ibanez", "models": ["RG", "AZ"], "establishedYear": 1957, "rating": 7 } - { "_id": 6, "make": "Strandberg", "models": ["Boden", "Salen"], "establishedYear": 1982 } - -The following ``Guitar`` class models the documents in this collection. - -.. literalinclude:: /includes/fundamentals/code-examples/specify-query/Guitar.cs - :language: csharp - :copyable: - :dedent: - -.. note:: - - The documents in the ``guitars`` collection use the camel-case naming - convention. The examples in this guide use a ``ConventionPack`` - to deserialize the fields in the collection into Pascal case and map them to - the properties in the ``Guitar`` class. - - To learn more about custom serialization, see :ref:`csharp-custom-serialization`. - -To learn more about class mapping, see :ref:`csharp-class-mapping`. - -The following code instantiates the ``_guitarsCollection`` object using the -``Guitar`` class as a type parameter. This type parameter causes the driver to -automatically serialize and deserialize the documents it sends to and receives -from MongoDB to instances of the ``Guitar`` class: - -.. code-block:: csharp - - private static IMongoCollection _guitarsCollection; - -Literal Values --------------- - -Literal value queries return documents with an exact match to your query filter. - -The following example specifies a query filter as a parameter to the ``Find()`` -method. The query matches all documents where the -``make`` field equals "Fender". - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } - -The following example uses builders to create a query filter that matches the -same documents as the preceding example: - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } - -.. tip:: Find All Documents - - Use an empty query filter to match all documents in the collection. Create - an empty query filter with builders as follows: - - .. code-block:: csharp - - var result = _guitarsCollection.Find(Builders.Filter.Empty).ToList(); - -To learn more about using builders, see :ref:`csharp-builders`. - -Comparison Operators --------------------- - -Comparison operators analyze the value in a document against the specified value -in your query filter. Common comparison operators include: - -.. list-table:: - :widths: 30 30 40 - :header-rows: 1 - - * - Operator - - Builder - - Description - - * - ``>`` - - ``Gt()`` - - Greater than - - * - ``<=`` - - ``Lte()`` - - Less than or equal to - - * - ``!=`` - - ``Ne()`` - - Not equal to - -For a full list of comparison operators, see the :manual:`Comparison -Query Operators ` page. - -The following example specifies a query filter as a parameter to the ``Find()`` -method. The query matches all documents where the ``establishedYear`` field is -greater than ``1985``. - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } - -The following example uses builders to create a query filter that matches the -same documents as the preceding example: - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } - - -To learn more about using builders, see :ref:`csharp-builders`. - -Logical Operators ------------------ - -Logical operators match documents using logic applied to the results of two or more -sets of expressions. The following is a list of some logical operators: - -.. list-table:: - :widths: 30 30 40 - :header-rows: 1 - - * - Operator - - Builder - - Description - - * - ``&&`` - - ``And()`` - - All expressions must evaluate to true. - - * - ``||`` - - ``Or()`` - - At least one expression must evaluate to true. - -For a full list of logical operators, see the :manual:`Logical -Query Operators ` page. - -The following example specifies a query filter as a parameter to the ``Find()`` -method. The query matches all documents where the -``establishedYear`` field is greater than or equal to ``1985``, and the ``make`` -field is not equal to "Kiesel". - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } - - -The following example uses builders to create a query filter that matches the -same documents as the preceding example: - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } - -To learn more about using builders, see :ref:`csharp-builders`. - -Array Operators ---------------- - -Array operators match documents based on the value or quantity of elements in an array -field. The following is a list of builder methods that use array operators: - -.. list-table:: - :widths: 40 60 - :header-rows: 1 - - * - Operator - - Description - - * - ``All()`` - - Matches documents if the array field contains all elements specified in - the query. - - * - ``Any()`` - - Matches documents if any element in the array field matches the specified - query filter. - - * - ``Size()`` - - Matches documents if the array field is a specified size. - -.. note:: - - The ``Any()`` builder uses the ``$elemMatch`` query operator. - - To learn more about the ``$elemMatch`` query selector, see - :manual:`$elemMatch `. - -For more information on the array operators, see the :manual:`Array -Query Operators ` page. - -The following example uses builders to create a query filter that matches all -documents that have 3 elements in the ``models`` field: - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } - { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } - { "_id" : 4, "make" : "Kiesel", "models" : ["Ares", "Vader", "Solo"], "establishedYear" : 2015, "rating" : null } - -To learn more about using builders, see :ref:`csharp-builders`. - -Element Operators ------------------ - -Element operators query data based on the presence or type of a field. - -For a full list of element operators, see the :manual:`Element -Query Operators ` page. - -The following example uses builders to create a query filter that matches all -documents that have a ``rating`` field: - -.. io-code-block:: - :copyable: - - .. input:: /includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 1, "make" : "Fender", "models" : ["Stratocaster", "Telecaster"], "establishedYear" : 1946, "rating" : 9 } - { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } - { "_id" : 3, "make" : "PRS", "models" : ["Silver Sky", "SE", "Custom"], "establishedYear" : 1985, "rating" : 9 } - { "_id" : 5, "make" : "Ibanez", "models" : ["RG", "AZ"], "establishedYear" : 1957, "rating" : 7 } - -To learn more about using builders, see :ref:`csharp-builders`. - -Evaluation Operators --------------------- - -Evaluation operators analyze data on individual fields, or on the entire collection's -documents. Some builder methods that use evaluation operators include ``Regex()`` -and ``Text()``. - -For a full list of evaluation operators, see the :manual:`Evaluation -Query Operators ` page. - -The following example uses builders to create a query filter that matches all -documents that have a value in the ``make`` field that starts with the letter -"G": - -.. io-code-block:: - :copyable: - - .. input:: ../../../includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs - :language: csharp - - .. output:: - :language: json - :visible: - - { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } - -To learn more about using builders, see :ref:`csharp-builders`. - -Additional Information ----------------------- - -For more information about the operators mentioned in this guide, see the -following Server Manual Entries: - -- :manual:`Comparison Query Operators ` -- :manual:`Logical Query Operators ` -- :manual:`Array Query Operators ` -- :manual:`Element Query Operators ` -- :manual:`Evaluation Query Operators ` - -To learn more about using Builders, see :ref:`csharp-builders`. - -To learn how to specify queries using LINQ, see :ref:`csharp-linq`. diff --git a/source/get-started.txt b/source/get-started.txt new file mode 100644 index 00000000..9076db62 --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,248 @@ +.. _csharp-get-started: + +=================================== +Get Started with the {+driver-short+} +=================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Connect your .NET application to a MongoDB Atlas cluster using the .NET/C# Driver, and run queries on sample data. + :keywords: quick start, tutorial, basics + +Overview +-------- + +The {+driver-short+} is a NuGet package that you can use to connect +to and communicate with MongoDB. This guide shows you how to create an +application that uses the {+driver-short+} to connect to a MongoDB cluster hosted on +MongoDB Atlas. + +.. tip:: + + MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB + deployments. You can create your own free (no credit card required) MongoDB Atlas + deployment by following the steps in this guide. + +Follow this guide to connect a sample {+language+} application to a MongoDB Atlas +deployment. If you prefer to connect to MongoDB using a different driver or +programming language, see our :driver:`list of official drivers <>`. + +.. _csharp-get-started-download-driver: + +Download the {+driver-short+} +---------------------------- + +.. procedure:: + :style: connected + + .. step:: Create a Project Directory + + In your shell, run the following commands to create a + directory called ``csharp-quickstart`` and initialize a {+framework+} project for + a new console application: + + .. code-block:: bash + + mkdir csharp-quickstart + cd csharp-quickstart + dotnet new console + + .. step:: Install the {+driver-short+} + + Run the following command to install the current version of the {+driver-short+} + as a dependency of your project: + + .. code-block:: bash + + dotnet add package MongoDB.Driver + +After you complete these steps, you have a new {+framework+} project +and the {+driver-short+} installed. + +.. _csharp-get-started-deploy-cluster: + +Deploy a MongoDB Atlas Cluster +------------------------------ + +You can create a free tier MongoDB deployment on MongoDB Atlas +to store and manage your data. MongoDB Atlas hosts and manages +your MongoDB database in the cloud. + +.. procedure:: + :style: connected + + .. step:: Create a Free MongoDB Deployment on Atlas + + Complete the :atlas:`Get Started with Atlas ` + guide to set up a new Atlas account and load sample data into a new free + tier MongoDB deployment. + + .. step:: Save your Credentials + + After you create your database user, save that user's + username and password to a safe location for use in an upcoming step. + +After you complete these steps, you have a new free tier MongoDB +deployment on Atlas, database user credentials, and sample data loaded +in your database. + +.. _csharp-get-started-connection-string: + +Create a Connection String +-------------------------- + +You can connect to your MongoDB deployment by providing a +**connection URI**, also called a *connection string*, which +instructs the driver on how to connect to a MongoDB deployment +and how to behave while connected. + +The connection string includes the hostname or IP address and +port of your deployment, the authentication mechanism, user credentials +when applicable, and connection options. + +.. tip:: + + To connect to a self-managed (non-Atlas) deployment, see + :ref:`csharp-connect-to-mongodb`. + +.. procedure:: + :style: connected + + .. step:: Find your MongoDB Atlas Connection String + + To retrieve your connection string for the deployment that + you created in the :ref:`previous step `, + log into your Atlas account and navigate to the + :guilabel:`Database` section and click the :guilabel:`Connect` button + for your new deployment. + + .. figure:: /includes/figures/atlas_connection_select_cluster.png + :alt: The connect button in the clusters section of the Atlas UI + + Proceed to the :guilabel:`Connect your application` section and select + "C# / .NET" from the :guilabel:`Driver` selection menu and the version + that best matches the version you installed from the :guilabel:`Version` + selection menu. + + Select the :guilabel:`Password (SCRAM)` authentication mechanism. + + Deselect the :guilabel:`Include full driver code example` option to view + the connection string. + + .. step:: Copy your Connection String + + Click the button on the right of the connection string to copy it to + your clipboard as shown in the following screenshot: + + .. figure:: /includes/figures/atlas_connection_copy_string.png + :alt: The connection string copy button in the Atlas UI + + .. step:: Update the Placeholders + + Paste this connection string into a file in your preferred text editor + and replace the ```` and ```` placeholders with + your database user's username and password. + + Save this file to a safe location for use in the next step. + + .. step:: Set an Environment Variable + + In your shell, run the following code to save your MongoDB + :ref:`connection string ` to an + environment variable. Replace ```` with the connection + string that you saved to a file in the previous step. + + .. code-block:: bash + + export MONGODB_URI="" + + .. note:: PowerShell + + If you're using Microsoft PowerShell, run the following command instead: + + .. code-block:: bash + + set MONGODB_URI="" + + Storing your credentials in an environment variable is safer than hardcoding them + in your source code. + +After completing these steps, you have a connection string that +contains your database username and password. + +.. _csharp-get-started-run-sample-query: + +Run a Sample Query +------------------ + +.. procedure:: + :style: connected + + .. step:: Create your {+lang-framework+} Application + + Copy and paste the following code into the ``Program.cs`` file in your application: + + .. literalinclude:: /includes/quick-start/Program.cs + :language: csharp + :dedent: + + .. step:: Run your Application + + In your shell, run the following command to start this application: + + .. code-block:: sh + + dotnet run csharp-quickstart.csproj + + The output includes details of the retrieved movie document: + + .. code-block:: none + + { + _id: ..., + plot: 'A young man is accidentally sent 30 years into the past...', + genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], + ... + title: 'Back to the Future', + ... + } + + .. tip:: + + If you encounter an error or see no output, ensure that you specified the + proper connection string, and that you loaded the + sample data. + +After you complete these steps, you have a working application that +uses the driver to connect to your MongoDB deployment, runs a query on +the sample data, and prints out the result. + +.. _csharp-get-started-next-steps: + +Next Steps +---------- + +Congratulations on completing the tutorial! + +In this tutorial, you created a {+language+} application that +connects to a MongoDB deployment hosted on MongoDB Atlas +and retrieves a document that matches a query. + +Learn more about the {+driver-short+} from the following resources: + +- Learn how to insert documents in the :ref:`` section. +- Learn how to find documents in the :ref:`` section. +- Learn how to update documents in the :ref:`` and + :ref:`` sections. +- Learn how to delete documents in the :ref:`` section. + +.. include:: /includes/get-started/quickstart-troubleshoot.rst \ No newline at end of file diff --git a/source/includes/atlas-sample-data.rst b/source/includes/atlas-sample-data.rst index 46d24320..bc1588a1 100644 --- a/source/includes/atlas-sample-data.rst +++ b/source/includes/atlas-sample-data.rst @@ -24,5 +24,5 @@ classes as models: .. include:: /includes/convention-pack-note.rst This collection is from the :atlas:`sample datasets ` provided -by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster +by Atlas. See the :ref:`` to learn how to create a free MongoDB cluster and load this sample data. \ No newline at end of file diff --git a/source/includes/code-examples/projection/MetaExamples.cs b/source/includes/code-examples/projection/MetaExamples.cs new file mode 100644 index 00000000..12253454 --- /dev/null +++ b/source/includes/code-examples/projection/MetaExamples.cs @@ -0,0 +1,198 @@ +using MongoDB.Bson; +using MongoDB.Driver; +using MongoDB.Driver.Search; + +namespace Projection; + +public class MetaExamples +{ + static string _uri = ""; + + static IMongoCollection movieCollection = new MongoClient(_uri) + .GetDatabase("sample_mflix") + .GetCollection("movies"); + + static IMongoCollection embeddedMovieCollection = new MongoClient(_uri) + .GetDatabase("sample_mflix") + .GetCollection("embedded_movies"); + + public static List MetaTextScoreExample() + { + // start metaTextScore + var filter = Builders.Filter.Text("future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaTextScore("score"); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end metaTextScore + + return results; + } + + public static List MetaExample() + { + // start meta + var filter = Builders.Filter.Text("future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .Meta(field: "score", metaFieldName: "textScore"); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end meta + + return results; + } + + public static List MetaScoreExample() + { + // start metaScore + var filter = Builders.Search.Text(m => m.Title, "future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaScore(m => m.ScoreDetails); + + var results = movieCollection + .Aggregate() + .Search(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end metaScore + + return results; + } + + public static List MetaScoreDetailsExample() + { + // start metaScoreDetails + var filter = Builders.Filter.Text("future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaScoreDetails(m => m.ScoreDetails); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end metaScoreDetails + + return results; + } + + public static List MetaSearchHighlightsExample() + { + // start metaSearchHighlights + var filter = Builders.Search.Text(path: m => m.Plot, query: "future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaSearchHighlights(m => m.Highlights); + + var results = movieCollection + .Aggregate() + .Search(filter, new SearchHighlightOptions (m => m.Plot)) + .Project(projection) + .Limit(1) + .ToList(); + // end metaSearchHighlights + + return results; + } + + public static List MetaSearchScoreExample() + { + // start metaSearchScore + var filter = Builders.Search.Text(m => m.Plot, "future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaSearchScore(m => m.Score); + + var results = movieCollection + .Aggregate() + .Search(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end metaSearchScore + + return results; + } + + public static List MetaSearchScoreDetailsExample() + { + // start metaSearchScoreDetails + var filter = Builders.Search.Text(m => m.Plot, "future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaSearchScore(m => m.Score) + .MetaSearchScoreDetails(m => m.SearchScoreDetails); + + var results = movieCollection + .Aggregate() + .Search(filter, new SearchOptions() { ScoreDetails = true}) + .Project(projection) + .Limit(1) + .ToList(); + // end metaSearchScoreDetails + + return results; + } + + public static List MetaSearchSequenceTokenExample() + { + // start metaSearchSequenceToken + var filter = Builders.Search.Text(m => m.Plot, "future"); + var projection = Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot) + .MetaSearchSequenceToken(m => m.PaginationToken); + + var results = movieCollection + .Aggregate() + .Search(filter) + .Limit(1) + .Project(projection) + .ToList(); + // end metaSearchSequenceToken + + return results; + } + + public static List MetaVectorSearchScoreExample() + { + // start metaVectorSearchScore + QueryVector vector = new[] { -0.0016261312, -0.028070757, -0.011342932, -0.012775794, -0.0027440966, 0.008683807, -0.02575152, -0.02020668, -0.010283281, -0.0041719596, 0.021392956, 0.028657231, -0.006634482, 0.007490867, 0.018593878, 0.0038187427, 0.029590257, -0.01451522, 0.016061379, 0.00008528442, -0.008943722, 0.01627464, 0.024311995, -0.025911469, 0.00022596726, -0.008863748, 0.008823762, -0.034921836, 0.007910728, -0.01515501, 0.035801545, -0.0035688248, -0.020299982, -0.03145631, -0.032256044, -0.028763862, -0.0071576433, -0.012769129, 0.012322609, -0.006621153, 0.010583182, 0.024085402, -0.001623632, 0.007864078, -0.021406285, 0.002554159, 0.012229307, -0.011762793, 0.0051682983, 0.0048484034, 0.018087378, 0.024325324, -0.037694257, -0.026537929, -0.008803768, -0.017767483, -0.012642504, -0.0062712682, 0.0009771782, -0.010409906, 0.017754154, -0.004671795, -0.030469967, 0.008477209, -0.005218282, -0.0058480743, -0.020153364, -0.0032805866, 0.004248601, 0.0051449724, 0.006791097, 0.007650814, 0.003458861, -0.0031223053, -0.01932697, -0.033615597, 0.00745088, 0.006321252, -0.0038154104, 0.014555207, 0.027697546, -0.02828402, 0.0066711367, 0.0077107945, 0.01794076, 0.011349596, -0.0052715978, 0.014755142, -0.019753495, -0.011156326, 0.011202978, 0.022126047, 0.00846388, 0.030549942, -0.0041386373, 0.018847128, -0.00033655585, 0.024925126, -0.003555496, -0.019300312, 0.010749794, 0.0075308536, -0.018287312, -0.016567878, -0.012869096, -0.015528221, 0.0078107617, -0.011156326, 0.013522214, -0.020646535, -0.01211601, 0.055928253, 0.011596181, -0.017247654, 0.0005939711, -0.026977783, -0.003942035, -0.009583511, -0.0055248477, -0.028737204, 0.023179034, 0.003995351, 0.0219661, -0.008470545, 0.023392297, 0.010469886, -0.015874773, 0.007890735, -0.009690142, -0.00024970944, 0.012775794, 0.0114762215, 0.013422247, 0.010429899, -0.03686786, -0.006717788, -0.027484283, 0.011556195, -0.036068123, -0.013915418, -0.0016327957, 0.0151016945, -0.020473259, 0.004671795, -0.012555866, 0.0209531, 0.01982014, 0.024485271, 0.0105431955, -0.005178295, 0.033162415, -0.013795458, 0.007150979, 0.010243294, 0.005644808, 0.017260984, -0.0045618312, 0.0024725192, 0.004305249, -0.008197301, 0.0014203656, 0.0018460588, 0.005015015, -0.011142998, 0.01439526, 0.022965772, 0.02552493, 0.007757446, -0.0019726837, 0.009503538, -0.032042783, 0.008403899, -0.04609149, 0.013808787, 0.011749465, 0.036388017, 0.016314628, 0.021939443, -0.0250051, -0.017354285, -0.012962398, 0.00006107364, 0.019113706, 0.03081652, -0.018114036, -0.0084572155, 0.009643491, -0.0034721901, 0.0072642746, -0.0090636825, 0.01642126, 0.013428912, 0.027724205, 0.0071243206, -0.6858542, -0.031029783, -0.014595194, -0.011449563, 0.017514233, 0.01743426, 0.009950057, 0.0029706885, -0.015714826, -0.001806072, 0.011856096, 0.026444625, -0.0010663156, -0.006474535, 0.0016161345, -0.020313311, 0.0148351155, -0.0018393943, 0.0057347785, 0.018300641, -0.018647194, 0.03345565, -0.008070676, 0.0071443142, 0.014301958, 0.0044818576, 0.003838736, -0.007350913, -0.024525259, -0.001142124, -0.018620536, 0.017247654, 0.007037683, 0.010236629, 0.06046009, 0.0138887605, -0.012122675, 0.037694257, 0.0055081863, 0.042492677, 0.00021784494, -0.011656162, 0.010276617, 0.022325981, 0.005984696, -0.009496873, 0.013382261, -0.0010563189, 0.0026507939, -0.041639622, 0.008637156, 0.026471283, -0.008403899, 0.024858482, -0.00066686375, -0.0016252982, 0.027590916, 0.0051449724, 0.0058647357, -0.008743787, -0.014968405, 0.027724205, -0.011596181, 0.0047650975, -0.015381602, 0.0043718936, 0.002159289, 0.035908177, -0.008243952, -0.030443309, 0.027564257, 0.042625964, -0.0033688906, 0.01843393, 0.019087048, 0.024578573, 0.03268257, -0.015608194, -0.014128681, -0.0033538956, -0.0028757197, -0.004121976, -0.032389335, 0.0034322033, 0.058807302, 0.010943064, -0.030523283, 0.008903735, 0.017500903, 0.00871713, -0.0029406983, 0.013995391, -0.03132302, -0.019660193, -0.00770413, -0.0038853872, 0.0015894766, -0.0015294964, -0.006251275, -0.021099718, -0.010256623, -0.008863748, 0.028550599, 0.02020668, -0.0012962399, -0.003415542, -0.0022509254, 0.0119360695, 0.027590916, -0.046971202, -0.0015194997, -0.022405956, 0.0016677842, -0.00018535563, -0.015421589, -0.031802863, 0.03814744, 0.0065411795, 0.016567878, -0.015621523, 0.022899127, -0.011076353, 0.02841731, -0.002679118, -0.002342562, 0.015341615, 0.01804739, -0.020566562, -0.012989056, -0.002990682, 0.01643459, 0.00042527664, 0.008243952, -0.013715484, -0.004835075, -0.009803439, 0.03129636, -0.021432944, 0.0012087687, -0.015741484, -0.0052016205, 0.00080890034, -0.01755422, 0.004811749, -0.017967418, -0.026684547, -0.014128681, 0.0041386373, -0.013742141, -0.010056688, -0.013268964, -0.0110630235, -0.028337335, 0.015981404, -0.00997005, -0.02424535, -0.013968734, -0.028310679, -0.027750863, -0.020699851, 0.02235264, 0.001057985, 0.00081639783, -0.0099367285, 0.013522214, -0.012016043, -0.00086471526, 0.013568865, 0.0019376953, -0.019020405, 0.017460918, -0.023045745, 0.008503866, 0.0064678704, -0.011509543, 0.018727167, -0.003372223, -0.0028690554, -0.0027024434, -0.011902748, -0.012182655, -0.015714826, -0.0098634185, 0.00593138, 0.018753825, 0.0010146659, 0.013029044, 0.0003521757, -0.017620865, 0.04102649, 0.00552818, 0.024485271, -0.009630162, -0.015608194, 0.0006718621, -0.0008418062, 0.012395918, 0.0057980907, 0.016221326, 0.010616505, 0.004838407, -0.012402583, 0.019900113, -0.0034521967, 0.000247002, -0.03153628, 0.0011038032, -0.020819811, 0.016234655, -0.00330058, -0.0032289368, 0.00078973995, -0.021952773, -0.022459272, 0.03118973, 0.03673457, -0.021472929, 0.0072109587, -0.015075036, 0.004855068, -0.0008151483, 0.0069643734, 0.010023367, -0.010276617, -0.023019087, 0.0068244194, -0.0012520878, -0.0015086699, 0.022046074, -0.034148756, -0.0022192693, 0.002427534, -0.0027124402, 0.0060346797, 0.015461575, 0.0137554705, 0.009230294, -0.009583511, 0.032629255, 0.015994733, -0.019167023, -0.009203636, 0.03393549, -0.017274313, -0.012042701, -0.0009930064, 0.026777849, -0.013582194, -0.0027590916, -0.017594207, -0.026804507, -0.0014236979, -0.022032745, 0.0091236625, -0.0042419364, -0.00858384, -0.0033905501, -0.020739838, 0.016821127, 0.022539245, 0.015381602, 0.015141681, 0.028817179, -0.019726837, -0.0051283115, -0.011489551, -0.013208984, -0.0047017853, -0.0072309524, 0.01767418, 0.0025658219, -0.010323267, 0.012609182, -0.028097415, 0.026871152, -0.010276617, 0.021912785, 0.0022542577, 0.005124979, -0.0019710176, 0.004518512, -0.040360045, 0.010969722, -0.0031539614, -0.020366628, -0.025778178, -0.0110030435, -0.016221326, 0.0036587953, 0.016207997, 0.003007343, -0.0032555948, 0.0044052163, -0.022046074, -0.0008822095, -0.009363583, 0.028230704, -0.024538586, 0.0029840174, 0.0016044717, -0.014181997, 0.031349678, -0.014381931, -0.027750863, 0.02613806, 0.0004136138, -0.005748107, -0.01868718, -0.0010138329, 0.0054348772, 0.010703143, -0.003682121, 0.0030856507, -0.004275259, -0.010403241, 0.021113047, -0.022685863, -0.023032416, 0.031429652, 0.001792743, -0.005644808, -0.011842767, -0.04078657, -0.0026874484, 0.06915057, -0.00056939584, -0.013995391, 0.010703143, -0.013728813, -0.022939114, -0.015261642, -0.022485929, 0.016807798, 0.007964044, 0.0144219175, 0.016821127, 0.0076241563, 0.005461535, -0.013248971, 0.015301628, 0.0085171955, -0.004318578, 0.011136333, -0.0059047225, -0.010249958, -0.018207338, 0.024645219, 0.021752838, 0.0007614159, -0.013648839, 0.01111634, -0.010503208, -0.0038487327, -0.008203966, -0.00397869, 0.0029740208, 0.008530525, 0.005261601, 0.01642126, -0.0038753906, -0.013222313, 0.026537929, 0.024671877, -0.043505676, 0.014195326, 0.024778508, 0.0056914594, -0.025951454, 0.017620865, -0.0021359634, 0.008643821, 0.021299653, 0.0041686273, -0.009017031, 0.04044002, 0.024378639, -0.027777521, -0.014208655, 0.0028623908, 0.042119466, 0.005801423, -0.028124074, -0.03129636, 0.022139376, -0.022179363, -0.04067994, 0.013688826, 0.013328944, 0.0046184794, -0.02828402, -0.0063412455, -0.0046184794, -0.011756129, -0.010383247, -0.0018543894, -0.0018593877, -0.00052024535, 0.004815081, 0.014781799, 0.018007403, 0.01306903, -0.020433271, 0.009043689, 0.033189073, -0.006844413, -0.019766824, -0.018767154, 0.00533491, -0.0024575242, 0.018727167, 0.0058080875, -0.013835444, 0.0040719924, 0.004881726, 0.012029372, 0.005664801, 0.03193615, 0.0058047553, 0.002695779, 0.009290274, 0.02361889, 0.017834127, 0.0049017193, -0.0036388019, 0.010776452, -0.019793482, 0.0067777685, -0.014208655, -0.024911797, 0.002385881, 0.0034988478, 0.020899786, -0.0025858153, -0.011849431, 0.033189073, -0.021312982, 0.024965113, -0.014635181, 0.014048708, -0.0035921505, -0.003347231, 0.030869836, -0.0017161017, -0.0061346465, 0.009203636, -0.025165047, 0.0068510775, 0.021499587, 0.013782129, -0.0024475274, -0.0051149824, -0.024445284, 0.006167969, 0.0068844, -0.00076183246, 0.030150073, -0.0055948244, -0.011162991, -0.02057989, -0.009703471, -0.020646535, 0.008004031, 0.0066378145, -0.019900113, -0.012169327, -0.01439526, 0.0044252095, -0.004018677, 0.014621852, -0.025085073, -0.013715484, -0.017980747, 0.0071043274, 0.011456228, -0.01010334, -0.0035321703, -0.03801415, -0.012036037, -0.0028990454, -0.05419549, -0.024058744, -0.024272008, 0.015221654, 0.027964126, 0.03182952, -0.015354944, 0.004855068, 0.011522872, 0.004771762, 0.0027874154, 0.023405626, 0.0004242353, -0.03132302, 0.007057676, 0.008763781, -0.0027057757, 0.023005757, -0.0071176565, -0.005238275, 0.029110415, -0.010989714, 0.013728813, -0.009630162, -0.029137073, -0.0049317093, -0.0008630492, -0.015248313, 0.0043219104, -0.0055681667, -0.013175662, 0.029723546, 0.025098402, 0.012849103, -0.0009996708, 0.03118973, -0.0021709518, 0.0260181, -0.020526575, 0.028097415, -0.016141351, 0.010509873, -0.022965772, 0.002865723, 0.0020493253, 0.0020509914, -0.0041419696, -0.00039695262, 0.017287642, 0.0038987163, 0.014795128, -0.014661839, -0.008950386, 0.004431874, -0.009383577, 0.0012604183, -0.023019087, 0.0029273694, -0.033135757, 0.009176978, -0.011023037, -0.002102641, 0.02663123, -0.03849399, -0.0044152127, 0.0004527676, -0.0026924468, 0.02828402, 0.017727496, 0.035135098, 0.02728435, -0.005348239, -0.001467017, -0.019766824, 0.014715155, 0.011982721, 0.0045651635, 0.023458943, -0.0010046692, -0.0031373003, -0.0006972704, 0.0019043729, -0.018967088, -0.024311995, 0.0011546199, 0.007977373, -0.004755101, -0.010016702, -0.02780418, -0.004688456, 0.013022379, -0.005484861, 0.0017227661, -0.015394931, -0.028763862, -0.026684547, 0.0030589928, -0.018513903, 0.028363993, 0.0044818576, -0.009270281, 0.038920518, -0.016008062, 0.0093902415, 0.004815081, -0.021059733, 0.01451522, -0.0051583014, 0.023765508, -0.017874114, -0.016821127, -0.012522544, -0.0028390652, 0.0040886537, 0.020259995, -0.031216389, -0.014115352, -0.009176978, 0.010303274, 0.020313311, 0.0064112223, -0.02235264, -0.022872468, 0.0052449396, 0.0005723116, 0.0037321046, 0.016807798, -0.018527232, -0.009303603, 0.0024858483, -0.0012662497, -0.007110992, 0.011976057, -0.007790768, -0.042999174, -0.006727785, -0.011829439, 0.007024354, 0.005278262, -0.017740825, -0.0041519664, 0.0085905045, 0.027750863, -0.038387362, 0.024391968, 0.00087721116, 0.010509873, -0.00038508154, -0.006857742, 0.0183273, -0.0037054466, 0.015461575, 0.0017394272, -0.0017944091, 0.014181997, -0.0052682655, 0.009023695, 0.00719763, -0.013522214, 0.0034422, 0.014941746, -0.0016711164, -0.025298337, -0.017634194, 0.0058714002, -0.005321581, 0.017834127, 0.0110630235, -0.03369557, 0.029190388, -0.008943722, 0.009363583, -0.0034222065, -0.026111402, -0.007037683, -0.006561173, 0.02473852, -0.007084334, -0.010110005, -0.008577175, 0.0030439978, -0.022712521, 0.0054582027, -0.0012620845, -0.0011954397, -0.015741484, 0.0129557345, -0.00042111133, 0.00846388, 0.008930393, 0.016487904, 0.010469886, -0.007917393, -0.011762793, -0.0214596, 0.000917198, 0.021672864, 0.010269952, -0.007737452, -0.010243294, -0.0067244526, -0.015488233, -0.021552904, 0.017127695, 0.011109675, 0.038067464, 0.00871713, -0.0025591573, 0.021312982, -0.006237946, 0.034628596, -0.0045251767, 0.008357248, 0.020686522, 0.0010696478, 0.0076708077, 0.03772091, -0.018700508, -0.0020676525, -0.008923728, -0.023298996, 0.018233996, -0.010256623, 0.0017860786, 0.009796774, -0.00897038, -0.01269582, -0.018527232, 0.009190307, -0.02372552, -0.042119466, 0.008097334, -0.0066778013, -0.021046404, 0.0019593548, 0.011083017, -0.0016028056, 0.012662497, -0.000059095124, 0.0071043274, -0.014675168, 0.024831824, -0.053582355, 0.038387362, 0.0005698124, 0.015954746, 0.021552904, 0.031589597, -0.009230294, -0.0006147976, 0.002625802, -0.011749465, -0.034362018, -0.0067844326, -0.018793812, 0.011442899, -0.008743787, 0.017474247, -0.021619547, 0.01831397, -0.009037024, -0.0057247817, -0.02728435, 0.010363255, 0.034415334, -0.024032086, -0.0020126705, -0.0045518344, -0.019353628, -0.018340627, -0.03129636, -0.0034038792, -0.006321252, -0.0016161345, 0.033642255, -0.000056075285, -0.005005019, 0.004571828, -0.0024075406, -0.00010215386, 0.0098634185, 0.1980148, -0.003825407, -0.025191706, 0.035161756, 0.005358236, 0.025111731, 0.023485601, 0.0023342315, -0.011882754, 0.018287312, -0.0068910643, 0.003912045, 0.009243623, -0.001355387, -0.028603915, -0.012802451, -0.030150073, -0.014795128, -0.028630573, -0.0013487226, 0.002667455, 0.00985009, -0.0033972147, -0.021486258, 0.009503538, -0.017847456, 0.013062365, -0.014341944, 0.005078328, 0.025165047, -0.015594865, -0.025924796, -0.0018177348, 0.010996379, -0.02993681, 0.007324255, 0.014475234, -0.028577257, 0.005494857, 0.00011725306, -0.013315615, 0.015941417, 0.009376912, 0.0025158382, 0.008743787, 0.023832154, -0.008084005, -0.014195326, -0.008823762, 0.0033455652, -0.032362677, -0.021552904, -0.0056081535, 0.023298996, -0.025444955, 0.0097301295, 0.009736794, 0.015274971, -0.0012937407, -0.018087378, -0.0039387033, 0.008637156, -0.011189649, -0.00023846315, -0.011582852, 0.0066411467, -0.018220667, 0.0060846633, 0.0376676, -0.002709108, 0.0072776037, 0.0034188742, -0.010249958, -0.0007747449, -0.00795738, -0.022192692, 0.03910712, 0.032122757, 0.023898797, 0.0076241563, -0.007397564, -0.003655463, 0.011442899, -0.014115352, -0.00505167, -0.031163072, 0.030336678, -0.006857742, -0.022259338, 0.004048667, 0.02072651, 0.0030156737, -0.0042119464, 0.00041861215, -0.005731446, 0.011103011, 0.013822115, 0.021512916, 0.009216965, -0.006537847, -0.027057758, -0.04054665, 0.010403241, -0.0056281467, -0.005701456, -0.002709108, -0.00745088, -0.0024841821, 0.009356919, -0.022659205, 0.004061996, -0.013175662, 0.017074378, -0.006141311, -0.014541878, 0.02993681, -0.00028448965, -0.025271678, 0.011689484, -0.014528549, 0.004398552, -0.017274313, 0.0045751603, 0.012455898, 0.004121976, -0.025458284, -0.006744446, 0.011822774, -0.015035049, -0.03257594, 0.014675168, -0.0039187097, 0.019726837, -0.0047251107, 0.0022825818, 0.011829439, 0.005391558, -0.016781142, -0.0058747325, 0.010309938, -0.013049036, 0.01186276, -0.0011246296, 0.0062112883, 0.0028190718, -0.021739509, 0.009883412, -0.0073175905, -0.012715813, -0.017181009, -0.016607866, -0.042492677, -0.0014478565, -0.01794076, 0.012302616, -0.015194997, -0.04433207, -0.020606548, 0.009696807, 0.010303274, -0.01694109, -0.004018677, 0.019353628, -0.001991011, 0.000058938927, 0.010536531, -0.17274313, 0.010143327, 0.014235313, -0.024152048, 0.025684876, -0.0012504216, 0.036601283, -0.003698782, 0.0007310093, 0.004165295, -0.0029157067, 0.017101036, -0.046891227, -0.017460918, 0.022965772, 0.020233337, -0.024072073, 0.017220996, 0.009370248, 0.0010363255, 0.0194336, -0.019606877, 0.01818068, -0.020819811, 0.007410893, 0.0019326969, 0.017887443, 0.006651143, 0.00067394477, -0.011889419, -0.025058415, -0.008543854, 0.021579562, 0.0047484366, 0.014062037, 0.0075508473, -0.009510202, -0.009143656, 0.0046817916, 0.013982063, -0.0027990784, 0.011782787, 0.014541878, -0.015701497, -0.029350337, 0.021979429, 0.01332228, -0.026244693, -0.0123492675, -0.003895384, 0.0071576433, -0.035454992, -0.00046984528, 0.0033522295, 0.039347045, 0.0005119148, 0.00476843, -0.012995721, 0.0024042083, -0.006931051, -0.014461905, -0.0127558, 0.0034555288, -0.0074842023, -0.030256703, -0.007057676, -0.00807734, 0.007804097, -0.006957709, 0.017181009, -0.034575284, -0.008603834, -0.005008351, -0.015834786, 0.02943031, 0.016861115, -0.0050849924, 0.014235313, 0.0051449724, 0.0025924798, -0.0025741523, 0.04289254, -0.002104307, 0.012969063, -0.008310596, 0.00423194, 0.0074975314, 0.0018810473, -0.014248641, -0.024725191, 0.0151016945, -0.017527562, 0.0018727167, 0.0002830318, 0.015168339, 0.0144219175, -0.004048667, -0.004358565, 0.011836103, -0.010343261, -0.005911387, 0.0022825818, 0.0073175905, 0.00403867, 0.013188991, 0.03334902, 0.006111321, 0.008597169, 0.030123414, -0.015474904, 0.0017877447, -0.024551915, 0.013155668, 0.023525586, -0.0255116, 0.017220996, 0.004358565, -0.00934359, 0.0099967085, 0.011162991, 0.03092315, -0.021046404, -0.015514892, 0.0011946067, -0.01816735, 0.010876419, -0.10124666, -0.03550831, 0.0056348112, 0.013942076, 0.005951374, 0.020419942, -0.006857742, -0.020873128, -0.021259667, 0.0137554705, 0.0057880944, -0.029163731, -0.018767154, -0.021392956, 0.030896494, -0.005494857, -0.0027307675, -0.006801094, -0.014821786, 0.021392956, -0.0018110704, -0.0018843795, -0.012362596, -0.0072176233, -0.017194338, -0.018713837, -0.024272008, 0.03801415, 0.00015880188, 0.0044951867, -0.028630573, -0.0014070367, -0.00916365, -0.026537929, -0.009576847, -0.013995391, -0.0077107945, 0.0050016865, 0.00578143, -0.04467862, 0.008363913, 0.010136662, -0.0006268769, -0.006591163, 0.015341615, -0.027377652, -0.00093136, 0.029243704, -0.020886457, -0.01041657, -0.02424535, 0.005291591, -0.02980352, -0.009190307, 0.019460259, -0.0041286405, 0.004801752, 0.0011787785, -0.001257086, -0.011216307, -0.013395589, 0.00088137644, -0.0051616337, 0.03876057, -0.0033455652, 0.00075850025, -0.006951045, -0.0062112883, 0.018140694, -0.006351242, -0.008263946, 0.018154023, -0.012189319, 0.0075508473, -0.044358727, -0.0040153447, 0.0093302615, -0.010636497, 0.032789204, -0.005264933, -0.014235313, -0.018393943, 0.007297597, -0.016114693, 0.015021721, 0.020033404, 0.0137688, 0.0011046362, 0.010616505, -0.0039453674, 0.012109346, 0.021099718, -0.0072842683, -0.019153694, -0.003768759, 0.039320387, -0.006747778, -0.0016852784, 0.018154023, 0.0010963057, -0.015035049, -0.021033075, -0.04345236, 0.017287642, 0.016341286, -0.008610498, 0.00236922, 0.009290274, 0.028950468, -0.014475234, -0.0035654926, 0.015434918, -0.03372223, 0.004501851, -0.012929076, -0.008483873, -0.0044685286, -0.0102233, 0.01615468, 0.0022792495, 0.010876419, -0.0059647025, 0.01895376, -0.0069976957, -0.0042952523, 0.017207667, -0.00036133936, 0.0085905045, 0.008084005, 0.03129636, -0.016994404, -0.014915089, 0.020100048, -0.012009379, -0.006684466, 0.01306903, 0.00015765642, -0.00530492, 0.0005277429, 0.015421589, 0.015528221, 0.032202728, -0.003485519, -0.0014286962, 0.033908837, 0.001367883, 0.010509873, 0.025271678, -0.020993087, 0.019846799, 0.006897729, -0.010216636, -0.00725761, 0.01818068, -0.028443968, -0.011242964, -0.014435247, -0.013688826, 0.006101324, -0.0022509254, 0.013848773, -0.0019077052, 0.017181009, 0.03422873, 0.005324913, -0.0035188415, 0.014128681, -0.004898387, 0.005038341, 0.0012320944, -0.005561502, -0.017847456, 0.0008538855, -0.0047884234, 0.011849431, 0.015421589, -0.013942076, 0.0029790192, -0.013702155, 0.0001199605, -0.024431955, 0.019926772, 0.022179363, -0.016487904, -0.03964028, 0.0050849924, 0.017487574, 0.022792496, 0.0012504216, 0.004048667, -0.00997005, 0.0076041627, -0.014328616, -0.020259995, 0.0005598157, -0.010469886, 0.0016852784, 0.01716768, -0.008990373, -0.001987679, 0.026417969, 0.023792166, 0.0046917885, -0.0071909656, -0.00032051947, -0.023259008, -0.009170313, 0.02071318, -0.03156294, -0.030869836, -0.006324584, 0.013795458, -0.00047151142, 0.016874444, 0.00947688, 0.00985009, -0.029883493, 0.024205362, -0.013522214, -0.015075036, -0.030603256, 0.029270362, 0.010503208, 0.021539574, 0.01743426, -0.023898797, 0.022019416, -0.0068777353, 0.027857494, -0.021259667, 0.0025758184, 0.006197959, 0.006447877, -0.00025200035, -0.004941706, -0.021246338, -0.005504854, -0.008390571, -0.0097301295, 0.027244363, -0.04446536, 0.05216949, 0.010243294, -0.016008062, 0.0122493, -0.0199401, 0.009077012, 0.019753495, 0.006431216, -0.037960835, -0.027377652, 0.016381273, -0.0038620618, 0.022512587, -0.010996379, -0.0015211658, -0.0102233, 0.007071005, 0.008230623, -0.009490209, -0.010083347, 0.024431955, 0.002427534, 0.02828402, 0.0035721571, -0.022192692, -0.011882754, 0.010056688, 0.0011904413, -0.01426197, -0.017500903, -0.00010985966, 0.005591492, -0.0077707744, -0.012049366, 0.011869425, 0.00858384, -0.024698535, -0.030283362, 0.020140035, 0.011949399, -0.013968734, 0.042732596, -0.011649498, -0.011982721, -0.016967745, -0.0060913274, -0.007130985, -0.013109017, -0.009710136 }; + + var options = new VectorSearchOptions() + { + IndexName = "vector_index", + NumberOfCandidates = 150 + }; + + // run query + var results = embeddedMovieCollection + .Aggregate() + .VectorSearch(movie => movie.PlotEmbedding, vector, 10, options) + .Project(Builders.Projection + .Include(movie => movie.Title) + .Include(movie => movie.Plot) + .MetaVectorSearchScore(m => m.Score)) + .ToList(); + // end metaVectorSearchScore + + return results; + } +} \ No newline at end of file diff --git a/source/includes/code-examples/projection/Movie.cs b/source/includes/code-examples/projection/Movie.cs new file mode 100644 index 00000000..8cc8046f --- /dev/null +++ b/source/includes/code-examples/projection/Movie.cs @@ -0,0 +1,30 @@ +public class Movie +{ + public ObjectId Id { get; set; } + + public string Title { get; set; } + + public List Genres { get; set; } + + public string Type { get; set; } + + public string Plot { get; set; } + + public List Highlights { get; set; } + + public string Score { get; set; } + + [BsonElement("scoreDetails")] + public SearchScoreDetails ScoreDetails { get; set; } + + [BsonElement("searchScoreDetails")] + public SearchScoreDetails SearchScoreDetails { get; set; } + + [BsonElement("paginationToken")] + public string PaginationToken { get; set; } + + public List Cast { get; set; } + + [BsonElement("plot_embedding")] + public float[] PlotEmbedding { get; set; } +} \ No newline at end of file diff --git a/source/includes/code-examples/projection/SliceExamples.cs b/source/includes/code-examples/projection/SliceExamples.cs new file mode 100644 index 00000000..b190a5a9 --- /dev/null +++ b/source/includes/code-examples/projection/SliceExamples.cs @@ -0,0 +1,67 @@ +using MongoDB.Bson; +using MongoDB.Driver; + +namespace Projection; + +public class SliceExamples +{ + static string _uri = ""; + + static IMongoCollection movieCollection = new MongoClient(_uri) + .GetDatabase("sample_mflix") + .GetCollection("movies"); + + public static List FirstThreeExample() + { + // start first three + var filter = Builders.Filter.Text("future"); + var projection = Builders + .Projection + .Slice(m => m.Cast, 3) + .Include(m => m.Cast); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end first three + + return results; + } + + public static List LastThreeExample() + { + // start last three + var filter = Builders.Filter.Text("future"); + var projection = Builders + .Projection + .Slice(m => m.Cast, -3) + .Include(m => m.Title); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end last three + + return results; + } + + public static List SkipFirstLimitThreeExample() + { + // start skip first limit three + var filter = Builders.Filter.Text("future"); + var projection = Builders + .Projection + .Slice(m => m.Cast, 1, 3) + .Include(m => m.Title); + + var results = movieCollection.Find(filter) + .Project(projection) + .Limit(1) + .ToList(); + // end skip first limit three + + return results; + } +} \ No newline at end of file diff --git a/source/includes/collation.rst b/source/includes/collation.rst new file mode 100644 index 00000000..e944268c --- /dev/null +++ b/source/includes/collation.rst @@ -0,0 +1,117 @@ +To configure collation for your operation, create an instance of the +`Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ class. + +The following table describes the parameters that the ``Collation`` constructor accepts. +It also lists the corresponding class property that you can use to read each +setting's value. + +.. list-table:: + :header-rows: 1 + :widths: 20 60 20 + + * - Parameter + - Description + - Class Property + + * - ``locale`` + - | Specifies the International Components for Unicode (ICU) locale. For a list of + supported locales, + see :manual:`Collation Locales and Default Parameters ` + in the {+mdb-server+} Manual. + | + | If you want to use simple binary comparison, use the ``Collation.Simple`` static + property to return a ``Collation`` object with the ``locale`` set to ``"simple"``. + | **Data Type**: {+string-data-type+} + - ``Locale`` + + * - ``caseLevel`` + - | *(Optional)* Specifies whether to include case comparison. + | + | When this argument is ``true``, the driver's behavior depends on the value of + the ``strength`` argument: + | + | - If ``strength`` is ``CollationStrength.Primary``, the driver compares base + characters and case. + | - If ``strength`` is ``CollationStrength.Secondary``, the driver compares base + characters, diacritics, other secondary differences, and case. + | - If ``strength`` is any other value, this argument is ignored. + | + | When this argument is ``false``, the driver doesn't include case comparison at + strength level ``Primary`` or ``Secondary``. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + - ``CaseLevel`` + + * - ``caseFirst`` + - | *(Optional)* Specifies the sort order of case differences during tertiary level comparisons. + | + | **Data Type**: `CollationCaseFirst <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollationCaseFirst.html>`__ + | **Default**: ``CollationCaseFirst.Off`` + - ``CaseFirst`` + + * - ``strength`` + - | *(Optional)* Specifies the level of comparison to perform, as defined in the + `ICU documentation `__. + | + | **Data Type**: `CollationStrength <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollationStrength.html>`__ + | **Default**: ``CollationStrength.Tertiary`` + - ``Strength`` + + * - ``numericOrdering`` + - | *(Optional)* Specifies whether the driver compares numeric strings as numbers. + | + | If this argument is ``true``, the driver compares numeric strings as numbers. + For example, when comparing the strings "10" and "2", the driver treats the values + as 10 and 2, and finds 10 to be greater. + | + | If this argument is ``false`` or excluded, the driver compares numeric strings + as strings. For example, when comparing the strings "10" and "2", the driver + compares one character at a time. Because "1" is less than "2", the driver finds + "10" to be less than "2". + | + | For more information, see :manual:`Collation Restrictions ` + in the {+mdb-server+} manual. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + - ``NumericOrdering`` + + * - ``alternate`` + - | *(Optional)* Specifies whether the driver considers whitespace and punctuation as base + characters for purposes of comparison. + | + | **Data Type**: `CollationAlternate <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollationAlternate.html>`__ + | **Default**: ``CollationAlternate.NonIgnorable`` (spaces and punctuation are + considered base characters) + - ``Alternate`` + + * - ``maxVariable`` + - | *(Optional)* Specifies which characters the driver considers ignorable when + the ``alternate`` argument is ``CollationAlternate.Shifted``. + | + | **Data Type**: `CollationMaxVariable <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollationMaxVariable.html>`__ + | **Default**: ``CollationMaxVariable.Punctuation`` (the driver ignores punctuation + and spaces) + - ``MaxVariable`` + + * - ``normalization`` + - | *(Optional)* Specifies whether the driver normalizes text as needed. + | + | Most text doesn't require normalization. For more information about + normalization, see the `ICU documentation `__. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + - ``Normalization`` + + * - ``backwards`` + - | *(Optional)* Specifies whether strings containing diacritics sort from the back of the string + to the front. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + - ``Backwards`` + +For more information about collation, see the :manual:`Collation ` +page in the {+mdb-server+} manual. \ No newline at end of file diff --git a/source/includes/figures/atlas_connection_copy_string.png b/source/includes/figures/atlas_connection_copy_string.png new file mode 100644 index 00000000..22f1a910 Binary files /dev/null and b/source/includes/figures/atlas_connection_copy_string.png differ diff --git a/source/includes/figures/atlas_connection_select_cluster.png b/source/includes/figures/atlas_connection_select_cluster.png new file mode 100644 index 00000000..52d827d6 Binary files /dev/null and b/source/includes/figures/atlas_connection_select_cluster.png differ diff --git a/source/includes/fundamentals/code-examples/Cursor.cs b/source/includes/fundamentals/code-examples/Cursor.cs new file mode 100644 index 00000000..c8de98a2 --- /dev/null +++ b/source/includes/fundamentals/code-examples/Cursor.cs @@ -0,0 +1,155 @@ +using System.Threading.Tasks; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MongoDB.Driver; + +public class Cursor +{ + // Replace with your connection string + private const string MongoConnectionString = ""; + + public static async Task Main(string[] args) + { + var mongoClient = new MongoClient(MongoConnectionString); + var database = mongoClient.GetDatabase("sample_restaurants"); + var collection = database.GetCollection("restaurants"); + + { + // start-cursor-iterate + var filter = Builders.Filter.Eq(r => r.Name, "Starbucks"); + + using (var cursor = collection.FindSync(filter)) + { + while (cursor.MoveNext()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-cursor-iterate + } + + { + // start-cursor-iterate-async + var filter = Builders.Filter.Eq(r => r.Name, "Starbucks"); + + using (var cursor = await collection.FindAsync(filter)) + { + while (await cursor.MoveNextAsync()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-cursor-iterate-async + } + + { + // start-cursor-iterate-to-cursor + var filter = Builders.Filter.Eq(r => r.Name, "Starbucks"); + + using (var cursor = collection.Find(filter).ToCursor()) + { + while (cursor.MoveNext()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-cursor-iterate-to-cursor + } + + { + // start-cursor-iterate-to-cursor-async + var filter = Builders.Filter.Eq(r => r.Name, "Starbucks"); + + using (var cursor = await collection.Find(filter).ToCursorAsync()) + { + while (await cursor.MoveNextAsync()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-cursor-iterate-to-cursor-async + } + + { + // start-cursor-to-list + var filter = Builders.Filter.Eq(r => r.Name, "Dunkin' Donuts"); + var results = collection.FindSync(filter).ToList(); + // end-cursor-to-list + } + + { + // start-cursor-to-list-async + var filter = Builders.Filter.Eq(r => r.Name, "Dunkin' Donuts"); + var results = (await collection.FindAsync(filter)).ToList(); + // end-cursor-to-list-async + } + + { + // start-tailable-cursor + var filter = Builders.Filter.Eq(r => r.Name, "Dunkin' Donuts"); + var options = new FindOptions + { + CursorType = CursorType.TailableAwait + }; + + using (var cursor = collection.FindSync(filter, options)) + { + while (cursor.MoveNext()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-tailable-cursor + } + + { + { + // start-tailable-cursor-async + var filter = Builders.Filter.Eq(r => r.Name, "Dunkin' Donuts"); + var options = new FindOptions + { + CursorType = CursorType.TailableAwait + }; + + using (var cursor = await collection.FindAsync(filter, options)) + { + while (await cursor.MoveNext()) + { + foreach (var restaurant in cursor.Current) + { + Console.WriteLine(restaurant.Name); + } + } + } + // end-tailable-cursor-async + } + } + + } +} + +// start-restaurant-class +[BsonIgnoreExtraElements] +public class Restaurant +{ + public ObjectId Id { get; set; } + + [BsonElement("name")] + public string Name { get; set; } +} +// end-restaurant-class \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/ExtendedJson.cs b/source/includes/fundamentals/code-examples/ExtendedJson.cs new file mode 100644 index 00000000..7a24d794 --- /dev/null +++ b/source/includes/fundamentals/code-examples/ExtendedJson.cs @@ -0,0 +1,40 @@ +using MongoDB.Bson; + +public class ExtendedJson +{ + public static void Main(string[] args) + { + { + // start-read-ejson + var ejson = "{\n\"_id\": { \"$oid\": \"573a1391f29313caabcd9637\" },\n \"createdAt\": { \"$date\": { \"$numberLong\": \"1601499609\" }},\n\"numViews\": { \"$numberLong\": \"36520312\" }\n}\n\n"; + + var document = BsonDocument.Parse(ejson); + Console.WriteLine(document.ToJson()); + // end-read-ejson + } + + { + // start-write-ejson + var document = new MyDocument(); + document.Id = ObjectId.GenerateNewId(); + document.CreatedAt = DateTime.UtcNow; + document.NumViews = 1234567890; + + var json = document.ToJson(new JsonWriterSettings + { + OutputMode = JsonOutputMode.CanonicalExtendedJson + }); + Console.WriteLine(json); + // end-write-ejson + } + } +} + +// start-custom-class +public class MyDocument +{ + public ObjectId Id { get; set; } + public DateTime CreatedAt { get; set; } + public long NumViews { get; set; } +} +// end-custom-class \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/ReplicaSetConfigs.cs b/source/includes/fundamentals/code-examples/ReplicaSetConfigs.cs index fcb35edd..cf7c2163 100644 --- a/source/includes/fundamentals/code-examples/ReplicaSetConfigs.cs +++ b/source/includes/fundamentals/code-examples/ReplicaSetConfigs.cs @@ -8,7 +8,7 @@ public static void Main(string[] args) var client = new MongoClient("mongodb://localhost:27017"); { // start-write-concern-client - var mongoClientSettings = MongoClientSettings.FromConnectionString(""); + var mongoClientSettings = MongoClientSettings.FromConnectionString(""); mongoClientSettings.WriteConcern = WriteConcern.WMajority; var mongoClient = new MongoClient(mongoClientSettings); // end-write-concern-client @@ -24,7 +24,7 @@ public static void Main(string[] args) { // start-read-concern-client - var mongoClientSettings = MongoClientSettings.FromConnectionString(""); + var mongoClientSettings = MongoClientSettings.FromConnectionString(""); mongoClientSettings.ReadConcern = ReadConcern.Majority; var mongoClient = new MongoClient(mongoClientSettings); // end-read-concern-client @@ -40,7 +40,7 @@ public static void Main(string[] args) { // start-read-preference-client - var mongoClientSettings = MongoClientSettings.FromConnectionString(""); + var mongoClientSettings = MongoClientSettings.FromConnectionString(""); mongoClientSettings.ReadPreference = ReadPreference.Secondary; var mongoClient = new MongoClient(mongoClientSettings); // end-read-preference-client @@ -53,5 +53,22 @@ public static void Main(string[] args) .WithReadPreference(ReadPreference.Secondary); // end-read-preference-collection } + + { + // start-retry-reads-writes + var mongoClientSettings = MongoClientSettings.FromConnectionString(""); + mongoClientSettings.RetryReads = false; + mongoClientSettings.RetryWrites = false; + var mongoClient = new MongoClient(mongoClientSettings); + // end-retry-reads-writes + } + + { + // start-retry-reads-writes-connection-string + var connectionString = "mongodb://localhost:27017/?retryReads=false&retryWrites=false"; + var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString); + var mongoClient = new MongoClient(mongoClientSettings); + // end-retry-reads-writes-connection-string + } } } \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs b/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs index 88e49dd3..b3ccce25 100644 --- a/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs +++ b/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs @@ -40,7 +40,7 @@ public class BinaryVectors public float[] ValuesFloat { get; set; } // end-binary-int-float-serialize - // start-to-query-vector +// start-to-query-vector var binaryVector = new BinaryVectorInt8(new sbyte[] { 0, 1, 2, 3, 4 }); var queryVector = binaryVector.ToQueryVector(); diff --git a/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs b/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs index d04587e3..badf8283 100644 --- a/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs +++ b/source/includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs @@ -24,7 +24,7 @@ public static void Main(string[] args) NumberOfCandidates = 150 }; - // run query + // Run vector search query var results = collection.Aggregate() .VectorSearch(movie => movie.PlotEmbedding, vector, 10, options) .Project(Builders.Projection @@ -32,7 +32,7 @@ public static void Main(string[] args) .Include(movie => movie.Plot)) .ToList(); - // print results + // Print the results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); @@ -46,13 +46,34 @@ private static void Setup() var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); - // Establish the connection to MongoDB and get the restaurants database + // Establish the connection to MongoDB and get the embedded_movies database var mongoClient = new MongoClient(_mongoConnectionString); - var restaurantsDatabase = mongoClient.GetDatabase("sample_mflix"); - collection = restaurantsDatabase.GetCollection("embedded_movies"); + var movieDatabase = mongoClient.GetDatabase("sample_mflix"); + collection = movieDatabase.GetCollection("embedded_movies"); + } + + private static void BuildersExample() + { + // start-builders-example + var pipeline = new EmptyPipelineDefinition() + .VectorSearch(m => m.PlotEmbedding, vector, 10, options) + .Project(Builders.Projection + .Include(m => m.Title) + .Include(m => m.Plot)); + // end-builders-example + } + + private static void LinqExample() + { + // start-linq-example + var results = collection.AsQueryable() + .VectorSearch(m => m.PlotEmbedding, vector, 10, options) + .Select(m => new { m.Title, m.Plot }); + // end-linq-example } } +// start-sample-class [BsonIgnoreExtraElements] public class Movie { @@ -61,4 +82,5 @@ public class Movie public string Title { get; set; } [BsonElement("plot_embedding")] public float[] PlotEmbedding { get; set; } -} \ No newline at end of file +} +// end-sample-class \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/connection/ConnectionOptions.cs b/source/includes/fundamentals/code-examples/connection/ConnectionOptions.cs new file mode 100644 index 00000000..0097a059 --- /dev/null +++ b/source/includes/fundamentals/code-examples/connection/ConnectionOptions.cs @@ -0,0 +1,855 @@ +using System.Net.Security; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Microsoft.Extensions.Logging; +using MongoDB.Driver; +using MongoDB.Driver.Core.Compression; +using MongoDB.Driver.Core.Configuration; +using MongoDB.Driver.Core.Events; + +namespace Connection; + +public class ConnectionOptions +{ + public void ConnectionUriExample() + { + // start-connection-uri + const string uri = "mongodb+srv:/localhost:27017/?connectTimeoutMS=60000&tls=true"; + // end-connection-uri + } + + public void MongoClientSettingsExample() + { + // start-mongo-client-settings + var settings = new MongoClientSettings() + { + Scheme = ConnectionStringScheme.MongoDBPlusSrv, + Server = new MongoServerAddress("localhost", 27017), + ConnectTimeout = TimeSpan.FromMilliseconds(60000), + UseTls = true + }; + + var client = new MongoClient(settings); + // end-mongo-client-settings + } + + public void FromConnectionStringExample() + { + // start-from-connection-string + const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; + var settings = MongoClientSettings.FromConnectionString(connectionUri); + settings.ServerApi = new ServerApi(ServerApiVersion.V1); + + var client = new MongoClient(settings); + // end-from-connection-string + } + + public void FromUrlExample() + { + // start-from-url + const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; + var url = new MongoUrl(connectionUri); + var settings = MongoClientSettings.FromUrl(url); + settings.ServerApi = new ServerApi(ServerApiVersion.V1); + + var client = new MongoClient(settings); + // end-from-url + } + + public void MongoUrlBuilderExample() + { + // start-mongo-url-builder + const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; + var builder = new MongoUrlBuilder(connectionUri) + { + ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream + }; + var url = builder.ToMongoUrl(); + + var client = new MongoClient(url); + // end-mongo-url-builder + } + + public void ReplicaSetName() + { + // start-settings-replica-set-name + var settings = new MongoClientSettings + { + ReplicaSetName = "yourReplicaSet", + }; + // end-settings-replica-set-name + + // start-builder-replica-set-name + var builder = new MongoUrlBuilder + { + ReplicaSetName = "yourReplicaSet", + }; + // end-builder-replica-set-name + } + + public void DirectConnection() + { + // start-settings-direct-connection + var settings = new MongoClientSettings + { + DirectConnection = true, + }; + // end-settings-direct-connection + + // start-builder-direct-connection + var builder = new MongoUrlBuilder + { + DirectConnection = true, + }; + // end-builder-direct-connection + } + + public void AllowInsecureTls() + { + // start-settings-allow-insecure-tls + var settings = new MongoClientSettings + { + AllowInsecureTls = true, + }; + // end-settings-allow-insecure-tls + + // start-builder-allow-insecure-tls + var builder = new MongoUrlBuilder + { + AllowInsecureTls = true, + }; + // end-builder-allow-insecure-tls + } + + public void UseTls() + { + // start-settings-use-tls + var settings = new MongoClientSettings + { + UseTls = true, + }; + // end-settings-use-tls + + // start-builder-use-tls + var builder = new MongoUrlBuilder + { + UseTls = true, + }; + // end-builder-use-tls + } + + public void ConnectTimeout() + { + // start-settings-connect-timeout + var settings = new MongoClientSettings + { + ConnectTimeout = TimeSpan.FromSeconds(60), + }; + // end-settings-connect-timeout + + // start-builder-connect-timeout + var builder = new MongoUrlBuilder + { + ConnectTimeout = TimeSpan.FromSeconds(60), + }; + // end-builder-connect-timeout + } + + public void SocketTimeout() + { + // start-settings-socket-timeout + var settings = new MongoClientSettings + { + SocketTimeout = TimeSpan.FromSeconds(60), + }; + // end-settings-socket-timeout + + // start-builder-socket-timeout + var builder = new MongoUrlBuilder + { + SocketTimeout = TimeSpan.FromSeconds(60), + }; + // end-builder-socket-timeout + } + + public void Compressors() + { + // start-settings-compressors + var settings = new MongoClientSettings + { + Compressors = new List() + { + new(CompressorType.Zlib), + new(CompressorType.Snappy) + } + }; + // end-settings-compressors + + // start-builder-compressors + var builder = new MongoUrlBuilder + { + Compressors = new List() + { + new(CompressorType.Zlib), + new(CompressorType.Snappy) + } + }; + // end-builder-compressors + } + + public void MaxConnecting() + { + // start-settings-max-connecting + var settings = new MongoClientSettings + { + MaxConnecting = 3, + }; + // end-settings-max-connecting + + // start-builder-max-connecting + var builder = new MongoUrlBuilder + { + MaxConnecting = 3, + }; + // end-builder-max-connecting + } + + public void MaxConnectionIdleTime() + { + // start-settings-max-connection-idle-time + var settings = new MongoClientSettings + { + MaxConnectionIdleTime = TimeSpan.FromMinutes(8), + }; + // end-settings-max-connection-idle-time + + // start-builder-max-connection-idle-time + var builder = new MongoUrlBuilder + { + MaxConnectionIdleTime = TimeSpan.FromMinutes(8), + }; + // end-builder-max-connection-idle-time + } + + public void MaxConnectionLifeTime() + { + // start-settings-max-connection-life-time + var settings = new MongoClientSettings + { + MaxConnectionLifeTime = TimeSpan.FromMinutes(40), + }; + // end-settings-max-connection-life-time + + // start-builder-max-connection-life-time + var builder = new MongoUrlBuilder + { + MaxConnectionLifeTime = TimeSpan.FromMinutes(40), + }; + // end-builder-max-connection-life-time + } + + public void MaxConnectionPoolSize() + { + // start-settings-max-connection-pool-size + var settings = new MongoClientSettings + { + MaxConnectionPoolSize = 150, + }; + // end-settings-max-connection-pool-size + + // start-builder-max-connection-pool-size + var builder = new MongoUrlBuilder + { + MaxConnectionPoolSize = 150, + }; + // end-builder-max-connection-pool-size + } + + public void MinConnectionPoolSize() + { + // start-settings-min-connection-pool-size + var settings = new MongoClientSettings + { + MinConnectionPoolSize = 3, + }; + // end-settings-min-connection-pool-size + + // start-builder-min-connection-pool-size + var builder = new MongoUrlBuilder + { + MinConnectionPoolSize = 3, + }; + // end-builder-min-connection-pool-size + } + + public void WaitQueueTimeout() + { + // start-settings-wait-queue-timeout + var settings = new MongoClientSettings + { + WaitQueueTimeout = TimeSpan.FromSeconds(30), + }; + // end-settings-wait-queue-timeout + + // start-builder-wait-queue-timeout + var builder = new MongoUrlBuilder + { + WaitQueueTimeout = TimeSpan.FromSeconds(30), + }; + // end-builder-wait-queue-timeout + } + + public void ReadConcern() + { + // start-settings-read-concern + var settings = new MongoClientSettings + { + ReadConcern = MongoDB.Driver.ReadConcern.Local, + }; + // end-settings-read-concern + } + + public void ReadConcernLevel() + { + // start-builder-read-concern-level + var builder = new MongoUrlBuilder + { + ReadConcernLevel = MongoDB.Driver.ReadConcernLevel.Local, + }; + // end-builder-read-concern-level + } + + public void ReadPreference() + { + // start-settings-read-preference + var settings = new MongoClientSettings + { + ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred, + }; + // end-settings-read-preference + + // start-builder-read-preference + var builder = new MongoUrlBuilder + { + ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred, + }; + // end-builder-read-preference + } + + public void Credential() + { + // start-settings-credential + var settings = new MongoClientSettings + { + Credential = MongoCredential.CreatePlainCredential( + databaseName: "admin", + username: "user", + password: "password" + ) + }; + // end-settings-credential + } + + public void BuilderAuthentication() + { + // start-builder-authentication + var builder = new MongoUrlBuilder + { + AuthenticationMechanism = "GSSAPI", + AuthenticationMechanismProperties = new Dictionary + { + { "SERVICE_NAME", "other" }, + { "CANONICALIZE_HOST_NAME", "true" } + }, + AuthenticationSource = "db" + }; + // end-builder-authentication + } + + public void HeartbeatInterval() + { + // start-settings-heartbeat-interval + var settings = new MongoClientSettings + { + HeartbeatInterval = TimeSpan.FromSeconds(5) + }; + // end-settings-heartbeat-interval + + // start-builder-heartbeat-interval + var builder = new MongoUrlBuilder + { + HeartbeatInterval = TimeSpan.FromSeconds(5) + }; + // end-builder-heartbeat-interval + } + + public void HeartbeatTimeout() + { + // start-settings-heartbeat-timeout + var settings = new MongoClientSettings + { + HeartbeatTimeout = TimeSpan.FromSeconds(5) + }; + // end-settings-heartbeat-timeout + + // start-builder-heartbeat-timeout + var builder = new MongoUrlBuilder + { + HeartbeatTimeout = TimeSpan.FromSeconds(5) + }; + // end-builder-heartbeat-timeout + } + + public void LocalThreshold() + { + // start-settings-local-threshold + var settings = new MongoClientSettings + { + LocalThreshold = TimeSpan.FromSeconds(15) + }; + // end-settings-local-threshold + + // start-builder-local-threshold + var builder = new MongoUrlBuilder + { + LocalThreshold = TimeSpan.FromSeconds(15) + }; + // end-builder-local-threshold + } + + public void ServerSelectionTimeout() + { + // start-settings-server-selection-timeout + var settings = new MongoClientSettings + { + ServerSelectionTimeout = TimeSpan.FromSeconds(30) + }; + // end-settings-server-selection-timeout + + // start-builder-server-selection-timeout + var builder = new MongoUrlBuilder + { + ServerSelectionTimeout = TimeSpan.FromSeconds(30) + }; + // end-builder-server-selection-timeout + } + + public void ApplicationName() + { + // start-settings-application-name + var settings = new MongoClientSettings + { + ApplicationName = "yourAppName", + }; + // end-settings-application-name + + // start-builder-application-name + var builder = new MongoUrlBuilder + { + ApplicationName = "yourAppName", + }; + // end-builder-application-name + } + + public void Ipv6() + { + // start-settings-ipv6 + var settings = new MongoClientSettings + { + IPv6 = true, + }; + // end-settings-ipv6 + + // start-builder-ipv6 + var builder = new MongoUrlBuilder + { + IPv6 = true, + }; + // end-builder-ipv6 + } + + public void LoadBalanced() + { + // start-settings-load-balanced + var settings = new MongoClientSettings + { + LoadBalanced = true, + }; + // end-settings-load-balanced + + // start-builder-load-balanced + var builder = new MongoUrlBuilder + { + LoadBalanced = true, + }; + // end-builder-load-balanced + } + + public void RetryReads() + { + // start-settings-retry-reads + var settings = new MongoClientSettings + { + RetryReads = false, + }; + // end-settings-retry-reads + + // start-builder-retry-reads + var builder = new MongoUrlBuilder + { + RetryReads = false, + }; + // end-builder-retry-reads + } + + public void RetryWrites() + { + // start-settings-retry-writes + var settings = new MongoClientSettings + { + RetryWrites = false, + }; + // end-settings-retry-writes + + // start-builder-retry-writes + var builder = new MongoUrlBuilder + { + RetryWrites = false, + }; + // end-builder-retry-writes + } + + public void Scheme() + { + // start-settings-scheme + var settings = new MongoClientSettings + { + Scheme = ConnectionStringScheme.MongoDBPlusSrv, + }; + // end-settings-scheme + + // start-builder-scheme + var builder = new MongoUrlBuilder + { + Scheme = ConnectionStringScheme.MongoDBPlusSrv, + }; + // end-builder-scheme + } + + public void Server() + { + // start-settings-server + var settings = new MongoClientSettings + { + Server = new MongoServerAddress("localhost", 27017) + }; + // end-settings-server + + // start-builder-server + var builder = new MongoUrlBuilder + { + Server = new MongoServerAddress("localhost", 27017) + }; + // end-builder-server + } + + public void ServerMonitoringMode() + { + // start-settings-server-monitoring-mode + var settings = new MongoClientSettings + { + ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream + }; + // end-settings-server-monitoring-mode + + // start-builder-server-monitoring-mode + var builder = new MongoUrlBuilder + { + ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream + }; + // end-builder-server-monitoring-mode + } + + public void Servers() + { + // start-settings-servers + var settings = new MongoClientSettings + { + Servers = new List() + { + new ("localhost", 27017), + new ("localhost", 27018) + } + }; + // end-settings-servers + + // start-builder-servers + var builder = new MongoUrlBuilder + { + Servers = new List() + { + new ("localhost", 27017), + new ("localhost", 27018) + } + }; + // end-builder-servers + } + + public void SrvMaxHosts() + { + // start-settings-srv-max-hosts + var settings = new MongoClientSettings + { + SrvMaxHosts = 5 + }; + // end-settings-srv-max-hosts + + // start-builder-srv-max-hosts + var builder = new MongoUrlBuilder + { + SrvMaxHosts = 5 + }; + // end-builder-srv-max-hosts + } + + public void Journal() + { + // start-builder-journal + var builder = new MongoUrlBuilder + { + Journal = true + }; + // end-builder-journal + } + + public void TlsDisableCertificateRevocationCheck() + { + // start-builder-tls-disable + var builder = new MongoUrlBuilder + { + TlsDisableCertificateRevocationCheck = true + }; + // end-builder-tls-disable + } + + public void W() + { + // start-builder-w + var builder = new MongoUrlBuilder + { + W = 2 + }; + // end-builder-w + } + + public void WTimeout() + { + // start-builder-w-timeout + var builder = new MongoUrlBuilder + { + WTimeout = TimeSpan.FromSeconds(5) + }; + // end-builder-w-timeout + } + + public void UsernamePassword() + { + // start-builder-username-password + var builder = new MongoUrlBuilder + { + Username = "user", + Password = "password" + }; + // end-builder-username-password + } + + public void FSync() + { + // start-builder-fsync + var builder = new MongoUrlBuilder + { + FSync = true + }; + // end-builder-fsync + } + + public void DatabaseName() + { + // start-builder-database-name + var builder = new MongoUrlBuilder + { + DatabaseName = "test_database" + }; + // end-builder-database-name + } + + public void SrvServiceName() + { + // start-settings-srv-service-name + var settings = new MongoClientSettings + { + SrvServiceName = "yourServiceName" + }; + // end-settings-srv-service-name + + // start-builder-srv-service-name + var builder = new MongoUrlBuilder + { + SrvServiceName = "yourServiceName" + }; + // end-builder-srv-service-name + } + + public void LibraryInfo() + { + // start-settings-library-info + var settings = new MongoClientSettings + { + LibraryInfo = new LibraryInfo("customLibraryName", "1.0.0") + }; + // end-settings-library-info + } + + public void TranslationOptions() + { + // start-settings-translation-options + var settings = new MongoClientSettings + { + TranslationOptions = new ExpressionTranslationOptions() + { + CompatibilityLevel = ServerVersion.Server80, + EnableClientSideProjections = true + } + }; + // end-settings-translation-options + } + + public void LoggingSettings() + { + // start-settings-logging-settings + var settings = new MongoClientSettings + { + LoggingSettings = new LoggingSettings( + LoggerFactory.Create(l => + l.SetMinimumLevel(LogLevel.Debug))) + }; + // end-settings-logging-settings + } + + public void ServerApi() + { + // start-settings-server-api + var settings = new MongoClientSettings + { + ServerApi = new ServerApi( + ServerApiVersion.V1, + strict: true, + deprecationErrors: true), + }; + // end-settings-server-api + } + + public void ReadEncoding() + { + // start-settings-read-encoding + var settings = new MongoClientSettings + { + ReadEncoding = new UTF8Encoding( + encoderShouldEmitUTF8Identifier: false, + throwOnInvalidBytes: true) + }; + // end-settings-read-encoding + } + + public void WriteEncoding() + { + // start-settings-write-encoding + var settings = new MongoClientSettings + { + WriteEncoding = new UTF8Encoding( + encoderShouldEmitUTF8Identifier: false, + throwOnInvalidBytes: true) + }; + // end-settings-write-encoding + } + + public void AutoEncryptionOptions() + { + // start-settings-auto-encryption-options + var settings = new MongoClientSettings + { + AutoEncryptionOptions = new AutoEncryptionOptions( + keyVaultNamespace: new CollectionNamespace( + databaseName: "keyvault", + collectionName: "datakeys"), + kmsProviders: new Dictionary> () + { + { "local", new Dictionary () { { "key", "" } } } + } + ), + }; + // end-settings-auto-encryption-options + } + + public void ClusterConfigurator() + { + // start-settings-cluster-configurator + var settings = new MongoClientSettings + { + ClusterConfigurator = builder => + { + builder + .Subscribe(e => + { + Console.WriteLine($"Cluster opened: Cluster ID = {e.ClusterId}"); + }) + .Subscribe(e => + { + Console.WriteLine($"Cluster description changed: {e.NewDescription}"); + }); + } + }; + // end-settings-cluster-configurator + } + + public void SslSettings() + { + // start-settings-ssl-settings + var settings = new MongoClientSettings(); + settings.SslSettings = new SslSettings() + { + CheckCertificateRevocation = false, + ClientCertificateSelectionCallback = new LocalCertificateSelectionCallback() { ... }, + ClientCertificates = new List() { ... }, + EnabledSslProtocols = SslProtocols.Tls13, + ServerCertificateValidationCallback = new RemoteCertificateValidationCallback() { ... } + }; + // end-settings-ssl-settings + } + + public void IsFrozen() + { + // start-settings-is-frozen + var settings = new MongoClientSettings(); + if (!settings.IsFrozen) + { + settings.RetryReads = false; + } + // end-settings-is-frozen + } + + public void WriteConcern() + { + // start-settings-write-concern + var settings = new MongoClientSettings(); + settings.WriteConcern = MongoDB.Driver.WriteConcern.Acknowledged; + settings.WriteConcern = new WriteConcern( + w: 1, + wTimeout: new TimeSpan(0, 0, 0, 30, 0), + fsync: true, + journal: true + ); + // end-settings-write-concern + } +} \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/connection/ConnectionTargets.cs b/source/includes/fundamentals/code-examples/connection/ConnectionTargets.cs new file mode 100644 index 00000000..e69de29b diff --git a/source/includes/fundamentals/code-examples/connection/LocalConnectionConfig.cs b/source/includes/fundamentals/code-examples/connection/LocalConnectionConfig.cs deleted file mode 100644 index 01d84c84..00000000 --- a/source/includes/fundamentals/code-examples/connection/LocalConnectionConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Connects to a server by using a URI with configuration options - -// start local connection config -using MongoDB.Driver; - -// Sets the connection URI -const string connectionUri = "mongodb+srv://sample.host:27017/?connectTimeoutMS=60000&tls=true"; - -// Creates a new client and connects to the server -var client = new MongoClient(connectionUri); -// end local connection config \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/connection/MongoClientSettings.cs b/source/includes/fundamentals/code-examples/connection/MongoClientSettings.cs deleted file mode 100644 index c0009679..00000000 --- a/source/includes/fundamentals/code-examples/connection/MongoClientSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Defines a MongoClientSettings object to pass settings to the client - -// start mongo client settings -using MongoDB.Driver; - -// Creates a MongoClientSettings object -var settings = new MongoClientSettings() -{ - Scheme = ConnectionStringScheme.MongoDB, - Server = new MongoServerAddress("localhost", 27017) -}; - -// Creates a new client and connects to the server -var client = new MongoClient(settings); -// end mongo client settings \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/connection/MongoClientSettingsConfig.cs b/source/includes/fundamentals/code-examples/connection/MongoClientSettingsConfig.cs deleted file mode 100644 index 04e8bea2..00000000 --- a/source/includes/fundamentals/code-examples/connection/MongoClientSettingsConfig.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Defines a MongoClientSettings object to pass configuration settings to the client - -// start mongo client settings config -//const string connectionUri = "mongodb+srv://sample.host:27017/?connectTimeoutMS=60000&tls=true"; - -// Creates a MongoClientSettings object -var settings = new MongoClientSettings() -{ - Scheme = ConnectionStringScheme.MongoDBPlusSrv, - Server = new MongoServerAddress("sample.host", 27017), - ConnectTimeout = new TimeSpan(0, 0, 60), - UseTls = true -}; - -// Creates a new client and connects to the server -var client = new MongoClient(settings); -// end mongo client settings config \ No newline at end of file diff --git a/source/includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs b/source/includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs index 46c53384..8f253a49 100644 --- a/source/includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs +++ b/source/includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs @@ -1,11 +1,37 @@ // Connects to a specific replica set by using a URI -// start replica set connection +// start-replica-set-connection-rs-name using MongoDB.Driver; // Sets the connection URI than includes the replica set name -const string connectionUri = "mongodb://sample.host1:27017/?replicaSet=sampleRS"; +const string connectionUri = "mongodb://host1:27017/?replicaSet=sampleRS"; // Creates a new client and connects to the server var client = new MongoClient(connectionUri); -// end replica set connection \ No newline at end of file +// end-replica-set-connection-rs-name + +// start-replica-set-connection-list +using MongoDB.Driver; + +// Sets the connection URI than includes the list of hosts in the replica set +const string connectionUri = "mongodb://host1:27017,host2:27017,host3:27017"; + +// Creates a new client and connects to the server +var client = new MongoClient(connectionUri); +// end-replica-set-connection-list + +// start-replica-set-direct-connection-string +using MongoDB.Driver; + +const string connectionUri = "mongodb://host1:27017/?directConnection=true"; +var client = new MongoClient(connectionUri); +// end-replica-set-direct-connection-string + +// start-replica-set-direct-connection-settings +using MongoDB.Driver; + +var settings = MongoClientSettings.FromConnectionString("mongodb://host1:27017"); +settings.DirectConnection = true; +var client = new MongoClient(settings); +// end-replica-set-direct-connection-settings + diff --git a/source/includes/fundamentals/code-examples/connection/ServerSelection.cs b/source/includes/fundamentals/code-examples/connection/ServerSelection.cs new file mode 100644 index 00000000..eaaabe17 --- /dev/null +++ b/source/includes/fundamentals/code-examples/connection/ServerSelection.cs @@ -0,0 +1,38 @@ +using MongoDB.Driver; +using MongoDB.Driver.Core.Clusters; +using MongoDB.Driver.Core.Clusters.ServerSelectors; +using MongoDB.Driver.Core.Servers; + +public class ServerSelection +{ + // Replace with your connection string + private const string MongoConnectionString = ""; + + public static void Main(string[] args) + { + { + // start-server-selector + var settings = MongoClientSettings.FromConnectionString(""); + var clusterConfigurator = builder => + { + builder.ConfigureCluster(c => + c.With(PreServerSelector: new RandomServerSelector())); + }; + + settings.ClusterConfigurator = clusterConfigurator; + var client = new MongoClient(settings); + // end-server-selector + } + } +} + +// start-custom-class +public class CustomServerSelector : IServerSelector +{ + public IEnumerable SelectServers(ClusterDescription cluster, + IEnumerable servers) + { + return servers.Where(server => server.Type == ServerType.ReplicaSetSecondary); + } +} +// end-custom-class diff --git a/source/includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs index 01bb7a9d..55c26c5c 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindAndBuilder.cs @@ -4,7 +4,7 @@ var filter = builder.And(builder.Gte(g => g.EstablishedYear, 1985), builder.Ne(r => r.Make, "Kiesel")); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs b/source/includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs index 946a1a7e..17e2937d 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindAndPOCO.cs @@ -1,6 +1,6 @@ // Finds all documents with an "establishedYear" value greater than 1985 // and a "make" value that is not equal to "Kiesel" -var results = _guitarsCollection.Find(g => g.EstablishedYear >= 1985 && r.Make != "Kiesel").ToList(); +var results = guitarCollection.Find(g => g.EstablishedYear >= 1985 && r.Make != "Kiesel").ToList(); foreach (var doc in results) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs index 4b346502..7d23f57a 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindEqBuilder.cs @@ -2,7 +2,7 @@ var filter = Builders.Filter.Eq(g => g.Make, "Fender"); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs b/source/includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs index ea031b67..a4c92c17 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindEqPOCO.cs @@ -1,5 +1,5 @@ // Finds all documents with a "make" value of "Fender" -var results = _guitarsCollection.Find(g => g.Make == "Fender").ToList(); +var results = guitarCollection.Find(g => g.Make == "Fender").ToList(); foreach (var doc in results) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs index 2860354f..438e33bb 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindExistsBuilder.cs @@ -2,7 +2,7 @@ var filter = Builders.Filter.Exists(g => g.Rating); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs index 466b56fb..afee42b9 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindGtBuilder.cs @@ -3,7 +3,7 @@ var filter = Builders.Filter.Gt(g => g.EstablishedYear, 1985); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs b/source/includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs index d3308414..7f92dcb1 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindGtPOCO.cs @@ -1,5 +1,5 @@ -// Finds all documents with am "establishedYear" value greater than 1985 -var results = _guitarsCollection.Find(g => g.EstablishedYear > 1985).ToList(); +// Finds all documents with an "establishedYear" value greater than 1985 +var results = guitarCollection.Find(g => g.EstablishedYear > 1985).ToList(); foreach (var doc in results) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs index efcc8c59..29e36a79 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindRegexBuilder.cs @@ -2,7 +2,7 @@ var filter = Builders.Filter.Regex(g => g.Make, "^G"); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs b/source/includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs index 02764816..7a1272b7 100644 --- a/source/includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs +++ b/source/includes/fundamentals/code-examples/specify-query/FindSizeBuilder.cs @@ -2,7 +2,7 @@ var filter = Builders.Filter.Size(g => g.Models, 3); // Finds all documents that match the filter -var result = _guitarsCollection.Find(filter).ToList(); +var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { diff --git a/source/includes/fundamentals/connection-options/allowInsecureTls.rst b/source/includes/fundamentals/connection-options/allowInsecureTls.rst new file mode 100644 index 00000000..2c942bd2 --- /dev/null +++ b/source/includes/fundamentals/connection-options/allowInsecureTls.rst @@ -0,0 +1,7 @@ +Specifies whether to relax TLS constraints as much as possible. This can include +allowing invalid certificates or hostname mismatches. The default value is ``false``. + +If this property is set to ``true`` and ``SslSettings.CheckCertificateRevocation`` +is set to ``false``, the {+driver-short+} will throw an exception. + +The following code example shows how to set this option to ``true``: \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/applicationName.rst b/source/includes/fundamentals/connection-options/applicationName.rst new file mode 100644 index 00000000..e2267756 --- /dev/null +++ b/source/includes/fundamentals/connection-options/applicationName.rst @@ -0,0 +1,4 @@ +The app name the driver passes to the server in the client metadata as part of +the connection handshake. The server prints this value to the MongoDB logs once +the connection is established. The value is also recorded in the slow query logs +and profile collections. The default value is ``null``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/compressors.rst b/source/includes/fundamentals/connection-options/compressors.rst new file mode 100644 index 00000000..c02bd7d3 --- /dev/null +++ b/source/includes/fundamentals/connection-options/compressors.rst @@ -0,0 +1,3 @@ +The preferred compression types, in order, for wire-protocol messages sent to +or received from the server. The driver uses the first of these compression types +that the server supports. The default value is ``null``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/connectTimeout.rst b/source/includes/fundamentals/connection-options/connectTimeout.rst new file mode 100644 index 00000000..6282d4fd --- /dev/null +++ b/source/includes/fundamentals/connection-options/connectTimeout.rst @@ -0,0 +1,2 @@ +The length of time the driver tries to establish a single TCP socket connection +to the server before timing out. The default value is 30 seconds. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/directConnection.rst b/source/includes/fundamentals/connection-options/directConnection.rst new file mode 100644 index 00000000..bc69995d --- /dev/null +++ b/source/includes/fundamentals/connection-options/directConnection.rst @@ -0,0 +1,8 @@ +Specifies whether to force dispatch **all** operations to the host. +If you specify this option, the driver doesn't accept the +:manual:`DNS seed list connection format. ` +You must use the :manual:`standard connection URI format ` +instead. The default value is ``false``. + +This property must be set to ``false`` if you specify more than one +host name. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/heartbeatInterval.rst b/source/includes/fundamentals/connection-options/heartbeatInterval.rst new file mode 100644 index 00000000..be42ae49 --- /dev/null +++ b/source/includes/fundamentals/connection-options/heartbeatInterval.rst @@ -0,0 +1,2 @@ +The interval between regular server-monitoring checks. Must be greater than or +equal to 500 milliseconds. The default value is ``10000`` milliseconds (10 seconds). \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/heartbeatTimeout.rst b/source/includes/fundamentals/connection-options/heartbeatTimeout.rst new file mode 100644 index 00000000..85424bb0 --- /dev/null +++ b/source/includes/fundamentals/connection-options/heartbeatTimeout.rst @@ -0,0 +1,2 @@ +The length of time a monitoring socket can be idle before timing out. The default value +is the value of the ``ConnectTimeout`` property. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/ipv6.rst b/source/includes/fundamentals/connection-options/ipv6.rst new file mode 100644 index 00000000..a23191ed --- /dev/null +++ b/source/includes/fundamentals/connection-options/ipv6.rst @@ -0,0 +1 @@ +Specifies whether the host address is in IPv6 format. The default value is ``false``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/loadBalanced.rst b/source/includes/fundamentals/connection-options/loadBalanced.rst new file mode 100644 index 00000000..cdb40261 --- /dev/null +++ b/source/includes/fundamentals/connection-options/loadBalanced.rst @@ -0,0 +1,9 @@ +Specifies whether the driver is connecting to a load balancer. You can set this +property to ``true`` only if all the following conditions are met: + +- You specify just one host name +- You're not connecting to a replica set +- You're not using the ``SrvMaxHosts`` property +- You're not using the ``DirectConnection`` property + +The default value is ``false``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/localThreshold.rst b/source/includes/fundamentals/connection-options/localThreshold.rst new file mode 100644 index 00000000..811db444 --- /dev/null +++ b/source/includes/fundamentals/connection-options/localThreshold.rst @@ -0,0 +1,3 @@ +The latency window for server eligibility. If a server's round trip takes longer +than the fastest server's round-trip time plus this value, the server isn't +eligible for selection. The default value is 15 milliseconds. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/maxConnecting.rst b/source/includes/fundamentals/connection-options/maxConnecting.rst new file mode 100644 index 00000000..b6ac4280 --- /dev/null +++ b/source/includes/fundamentals/connection-options/maxConnecting.rst @@ -0,0 +1,2 @@ +The greatest number of connections a driver's connection pool may be +establishing concurrently. The default value is ``2``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/maxConnectionIdleTime.rst b/source/includes/fundamentals/connection-options/maxConnectionIdleTime.rst new file mode 100644 index 00000000..1bab20a5 --- /dev/null +++ b/source/includes/fundamentals/connection-options/maxConnectionIdleTime.rst @@ -0,0 +1,2 @@ +The length of time a connection can be idle before the driver closes it. The default +value is 10 minutes. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/maxConnectionLifetime.rst b/source/includes/fundamentals/connection-options/maxConnectionLifetime.rst new file mode 100644 index 00000000..6eeadfe7 --- /dev/null +++ b/source/includes/fundamentals/connection-options/maxConnectionLifetime.rst @@ -0,0 +1,2 @@ +The length of time a connection can be pooled before expiring. The default value is +30 minutes. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/maxConnectionPoolSize.rst b/source/includes/fundamentals/connection-options/maxConnectionPoolSize.rst new file mode 100644 index 00000000..1eeedced --- /dev/null +++ b/source/includes/fundamentals/connection-options/maxConnectionPoolSize.rst @@ -0,0 +1,2 @@ +The greatest number of clients or connections the driver can create in its +connection pool. This count includes connections in use. The default value is ``100``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/minConnectionPoolSize.rst b/source/includes/fundamentals/connection-options/minConnectionPoolSize.rst new file mode 100644 index 00000000..eb3d4a3e --- /dev/null +++ b/source/includes/fundamentals/connection-options/minConnectionPoolSize.rst @@ -0,0 +1,3 @@ +The number of connections the driver creates and keeps in the connection +pool even when no operations are occurring. This count includes connections +in use. The default value is ``0``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/readPreference.rst b/source/includes/fundamentals/connection-options/readPreference.rst new file mode 100644 index 00000000..905d5e66 --- /dev/null +++ b/source/includes/fundamentals/connection-options/readPreference.rst @@ -0,0 +1,6 @@ +The client's default read-preference settings. ``MaxStaleness`` represents the +longest replication lag, in wall-clock time, that a secondary can experience and +still be eligible for server selection. The default value is ``ReadPreference.Primary``. +Specifying ``-1`` means no maximum. +See :manual:`Read Preference ` in the {+mdb-server+} manual +for more information. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/replicaSetName.rst b/source/includes/fundamentals/connection-options/replicaSetName.rst new file mode 100644 index 00000000..8c085fc9 --- /dev/null +++ b/source/includes/fundamentals/connection-options/replicaSetName.rst @@ -0,0 +1 @@ +The name of the replica set to connect to. The default value is ``null``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/retryReads.rst b/source/includes/fundamentals/connection-options/retryReads.rst new file mode 100644 index 00000000..2d37750b --- /dev/null +++ b/source/includes/fundamentals/connection-options/retryReads.rst @@ -0,0 +1 @@ +Enables retryable reads. The default value is ``true``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/retryWrites.rst b/source/includes/fundamentals/connection-options/retryWrites.rst new file mode 100644 index 00000000..24c430b7 --- /dev/null +++ b/source/includes/fundamentals/connection-options/retryWrites.rst @@ -0,0 +1 @@ +Enables retryable writes. The default value is ``true``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/scheme.rst b/source/includes/fundamentals/connection-options/scheme.rst new file mode 100644 index 00000000..894343ed --- /dev/null +++ b/source/includes/fundamentals/connection-options/scheme.rst @@ -0,0 +1,10 @@ +Specifies whether to use the standard connection string format (``MongoDB``) +or the DNS seed list format (``MongoDBPlusSrv``). The available values for this +property are defined in the `ConnectionStringScheme <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Configuration.ConnectionStringScheme.html>`__ +enum. The default value is ``ConnectionStringScheme.MongoDB``. +See :manual:`Connection Strings ` in the {+mdb-server+} +manual for more information about connection string formats. + +If the ``DirectConnection`` property is set to ``true`` and you +try to use the DNS seed list format, the {+driver-short+} will throw an +exception. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/server.rst b/source/includes/fundamentals/connection-options/server.rst new file mode 100644 index 00000000..c6d294e6 --- /dev/null +++ b/source/includes/fundamentals/connection-options/server.rst @@ -0,0 +1,2 @@ +The host and port number where MongoDB is running. The default value is +``localhost:27017``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/serverMonitoringMode.rst b/source/includes/fundamentals/connection-options/serverMonitoringMode.rst new file mode 100644 index 00000000..cf9f0f7a --- /dev/null +++ b/source/includes/fundamentals/connection-options/serverMonitoringMode.rst @@ -0,0 +1,8 @@ +Specifies the server monitoring protocol to use. The available values for this +property are defined in the `ServerMonitoringMode <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Servers.ServerMonitoringMode.html>`__ +enum. The default value is ``Auto``. + +When this option is set to ``Auto`` the monitoring mode is determined +by the environment in which the driver is running. The driver +uses polling mode in function-as-a-service (FaaS) environments, +such as AWS Lambda, and the streaming mode in other environments. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/serverSelectionTimeout.rst b/source/includes/fundamentals/connection-options/serverSelectionTimeout.rst new file mode 100644 index 00000000..7dd4c9ff --- /dev/null +++ b/source/includes/fundamentals/connection-options/serverSelectionTimeout.rst @@ -0,0 +1,2 @@ +The length of time the driver tries to select a server before timing out. The default +value is 30 seconds. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/servers.rst b/source/includes/fundamentals/connection-options/servers.rst new file mode 100644 index 00000000..61c3a4d0 --- /dev/null +++ b/source/includes/fundamentals/connection-options/servers.rst @@ -0,0 +1,2 @@ +The cluster members where MongoDB is running. The default value is +``localhost:27017``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/socketTimeout.rst b/source/includes/fundamentals/connection-options/socketTimeout.rst new file mode 100644 index 00000000..56fde85e --- /dev/null +++ b/source/includes/fundamentals/connection-options/socketTimeout.rst @@ -0,0 +1,2 @@ +The length of time the driver tries to send or receive on a socket before +timing out. The default value is set by the operating system. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/srvMaxHosts.rst b/source/includes/fundamentals/connection-options/srvMaxHosts.rst new file mode 100644 index 00000000..10cde05f --- /dev/null +++ b/source/includes/fundamentals/connection-options/srvMaxHosts.rst @@ -0,0 +1,7 @@ +The greatest number of SRV results to randomly select when initially populating +the seedlist or, during SRV polling, adding new hosts to the topology. The default +value is ``0``. + +You can use this property only if the connection-string scheme is set +to ``ConnectionStringScheme.MongoDBPlusSrv``. You cannot use it when connecting +to a replica set. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/srvServiceName.rst b/source/includes/fundamentals/connection-options/srvServiceName.rst new file mode 100644 index 00000000..beef9e1e --- /dev/null +++ b/source/includes/fundamentals/connection-options/srvServiceName.rst @@ -0,0 +1,14 @@ +The service name of the `SRV resource records `__ +that the driver retrieves to construct your seedlist. The driver uses the service name to +create the SRV URI, which matches the following format: + +.. code-block:: + + _{srvServiceName}._tcp.{hostname}.{domainname} + +This property overrides the default service name for SRV lookup in +discovery and polling. The default value is ``"mongodb"``. + +You can use this property only if the connection-string scheme is set +to ``ConnectionStringScheme.MongoDBPlusSrv``. You cannot use it when connecting +to a replica set. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/useTls.rst b/source/includes/fundamentals/connection-options/useTls.rst new file mode 100644 index 00000000..fe8de021 --- /dev/null +++ b/source/includes/fundamentals/connection-options/useTls.rst @@ -0,0 +1,3 @@ +Specifies whether to require TLS for connections to the server. If you use +a scheme of ``"mongodb+srv"`` or specify other TLS options, +this option defaults to ``true``. Otherwise, it defaults to ``false``. \ No newline at end of file diff --git a/source/includes/fundamentals/connection-options/waitQueueTimeout.rst b/source/includes/fundamentals/connection-options/waitQueueTimeout.rst new file mode 100644 index 00000000..3f48220f --- /dev/null +++ b/source/includes/fundamentals/connection-options/waitQueueTimeout.rst @@ -0,0 +1,2 @@ +The length of time the driver tries to check out a connection from a +server's connection pool before timing out. The default value is two minutes. \ No newline at end of file diff --git a/source/includes/get-started/quickstart-troubleshoot.rst b/source/includes/get-started/quickstart-troubleshoot.rst new file mode 100644 index 00000000..7ad83bce --- /dev/null +++ b/source/includes/get-started/quickstart-troubleshoot.rst @@ -0,0 +1,6 @@ +.. note:: + + If you run into issues on this step, ask for help in the + :community-forum:`MongoDB Community Forums ` + or submit feedback by using the :guilabel:`Rate this page` + tab on the right or bottom right side of this page. diff --git a/source/includes/linq-vs-builders.rst b/source/includes/linq-vs-builders.rst new file mode 100644 index 00000000..2d016a5a --- /dev/null +++ b/source/includes/linq-vs-builders.rst @@ -0,0 +1,8 @@ +.. tip:: LINQ or Builders? + + If you're used to programming in {+language+}, consider using LINQ because of its similar feel + to programming in native {+language+}. If you have prior experience with other MongoDB drivers, + consider using ``Builder`` classes because of their consistency with other drivers. + + We encourage experimenting with both approaches to determine the most suitable mechanism + for your purposes. \ No newline at end of file diff --git a/source/includes/page-templates/update/update.rst b/source/includes/page-templates/update/update.rst index 330c7df8..a468442d 100644 --- a/source/includes/page-templates/update/update.rst +++ b/source/includes/page-templates/update/update.rst @@ -164,8 +164,8 @@ The ``UpdateOptions`` class contains the following properties: * - ``Collation`` - Specifies the kind of language collation to use when sorting - results. See :manual:`the {+mdb-server+} manual` - for more information on collation. + results. See the + :ref:`` section of this page for more information. **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ @@ -215,6 +215,13 @@ The ``UpdateOptions`` class contains the following properties: **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__ +.. _csharp-update-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Return Value ------------ @@ -262,7 +269,9 @@ Additional Information |instruqt-lab-instructions| -For runnable examples of the update operations, see the |usage-examples-link| page. +For runnable examples of the update operations, see the following usage examples: + +|usage-examples-links| To learn more about creating query filters, see the :ref:`csharp-specify-query` guide. diff --git a/source/includes/project/atlas-only-note.rst b/source/includes/project/atlas-only-note.rst new file mode 100644 index 00000000..c44681f7 --- /dev/null +++ b/source/includes/project/atlas-only-note.rst @@ -0,0 +1,3 @@ +.. note:: Atlas Search Only + + This method is available only when projecting the results of an Atlas Search. \ No newline at end of file diff --git a/source/includes/quick-start/Program.cs b/source/includes/quick-start/Program.cs index a050d16d..62da7c08 100644 --- a/source/includes/quick-start/Program.cs +++ b/source/includes/quick-start/Program.cs @@ -4,7 +4,7 @@ var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI"); if (connectionString == null) { - Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/quick-start/#set-your-connection-string"); + Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/get-started/create-connection-string"); Environment.Exit(0); } diff --git a/source/includes/quick-start/query-output.rst b/source/includes/quick-start/query-output.rst index 971b7e10..1f51cc67 100644 --- a/source/includes/quick-start/query-output.rst +++ b/source/includes/quick-start/query-output.rst @@ -1,4 +1,4 @@ -When you run ``Program.cs``, it should output the details of the following movie from +When you run ``Program.cs``, it outputs the details of the following movie from the sample dataset: .. code-block:: json diff --git a/source/includes/troubleshooting/server-selection-timeout.rst b/source/includes/troubleshooting/server-selection-timeout.rst new file mode 100644 index 00000000..1f1b67f9 --- /dev/null +++ b/source/includes/troubleshooting/server-selection-timeout.rst @@ -0,0 +1,66 @@ +Driver Throws a Timeout During Server Selection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Each driver operation requires that you choose a server that +satisfies the :manual:`server selection criteria +`. If you do not select an appropriate +server within the `server selection timeout <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.ServerSelectionTimeout.html>`__, the driver throws a +server selection timeout exception. The exception looks similar to the +following: + +.. code-block:: none + + A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. + Client view of cluster state is + { + ClusterId : "1", + Type : "Unknown", + State : "Disconnected", + Servers : + [{ + ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }", + EndPoint: "Unspecified/localhost:27017", + ReasonChanged: "Heartbeat", + State: "Disconnected", + ServerVersion: , + TopologyVersion: , + Type: "Unknown", + HeartbeatException: "" + }] + }. + +The error message consists of multiple parts: + +1. The server selection timeout (30000 ms). +#. The server selectors considered (``CompositeServerSelector`` + containing ``AreSessionsSupportedServerSelector``, + ``LatencyLimitingServerSelector``, and + ``OperationsCountServerSelector``). +#. The driver’s current view of the cluster topology. The list of + servers that the driver is aware of is a key part of this view. Each + server description contains an exhaustive description of its current + state including information about an endpoint, a server version, a + server type, and its current health state. If the server encounters issues in + reporting its health, ``HeartbeatException`` contains the exception from the + last failed heartbeat. Analyzing the ``HeartbeatException`` on each + cluster node can assist in diagnosing most server selection issues. + The following heartbeat exceptions are common: + + * ``No connection could be made because the target machine actively + refused it``: The driver cannot see this cluster node. This might be + because the cluster node has crashed, a firewall is preventing + network traffic from reaching the cluster node or port, or some other + network error is preventing traffic from being successfully routed to + the cluster node. + * ``Attempted to read past the end of the stream``: This error + happens when the driver cannot connect to the cluster nodes due to a + network error, misconfigured firewall, or other network issue. To + address this exception, ensure that all cluster nodes are reachable. + This error commonly occurs when the client machine’s IP address is + not configured in the Atlas IPs Access List, which you can find under + the :guilabel:`Network Access` tab for your Atlas Project. + * ``The remote certificate is invalid according to the validation + procedure``: This error typically indicates a TLS/SSL-related problem + such as an expired/invalid certificate or an untrusted root CA. You + can use tools like ``openssl s_client`` to debug TLS/SSL-related + certificate problems. diff --git a/source/includes/troubleshooting/unsupported-filter-expression.rst b/source/includes/troubleshooting/unsupported-filter-expression.rst new file mode 100644 index 00000000..69344be0 --- /dev/null +++ b/source/includes/troubleshooting/unsupported-filter-expression.rst @@ -0,0 +1,60 @@ +.. _csharp-faq-unsupported-expressions: + +``Unsupported filter`` or ``Expression not supported`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you use a LINQ or builder expression that isn't available in the Query API, +you might receive an ``Unsupported filter ...`` or ``Expression not +supported ...`` exception message. +An expression might not be available in the following cases: + +1. You are attempting to use a {+lang-framework+} feature that doesn't have an + equivalent MongoDB representation. For example, {+lang-framework+} and MongoDB have + different semantics around collations. +#. The driver doesn't support a particular transformation from the LINQ or + builder expression into the Query API. This might happen because the + provided query has no Query API translation or because a feature hasn't been + implemented in the driver. + +If you receive one of these exceptions, try the following steps: + +1. Use the `{+analyzer+} + `__ to analyze your + expressions. +#. Simplify your query where possible. +#. Provide a query as a ``BsonDocument`` object or JSON string. All + definition classes, such as ``FilterDefinition``, + ``ProjectionDefinition``, and ``PipelineDefinition``, support implicit + conversion from ``BsonDocument`` objects or JSON strings. For example, the + following filters are equivalent when used in a query or + aggregation: + + .. code-block:: csharp + + FilterDefinition typedFilter = Builders.Filter.Eq(e => e.A, 1); + FilterDefinition bsonFilter = new BsonDocument {{ "a", 1 }}; + FilterDefinition jsonFilter = "{ a : 1 }"; + +You can combine ``BsonDocument`` objects, JSON strings, POCOs in the same +query, as shown in the following example: + +.. code-block:: csharp + + FilterDefinition filter = Builders.Filter + .And(Builders.Filter + .Eq(e => e.A, 1), BsonDocument + .Parse("{ b : 2 }")); + +.. note:: + + If you use a ``BsonDocument`` object or JSON string, your field names must match + the case-sensitive names stored by the server. For example, when referencing + the ``_id`` field, you must refer to it by using the field name ``_id``. + + Because the Query API doesn't recognize + :ref:`manual class mappings `, + BSON serialization attributes, or serialization conventions, you can't use these + mechanisms to change field names. For example, if a document contains a field named + ``FirstName`` annotated with ``[BsonElement("first_name")]``, you must refer to it + as ``first_name`` in ``BsonDocument`` or JSON string definitions. + diff --git a/source/includes/vector-search-intro.rst b/source/includes/vector-search-intro.rst index c930af0b..c380225d 100644 --- a/source/includes/vector-search-intro.rst +++ b/source/includes/vector-search-intro.rst @@ -4,7 +4,7 @@ defined Atlas Vector Search index before you can perform a vector search on your .. tip:: - To obtain the sample dataset used in the following example, see :ref:`csharp-quickstart`. + To obtain the sample dataset used in the following example, see :ref:`csharp-get-started`. To create the sample Atlas Vector Search index used in the following example, see :atlas:`Create an Atlas Vector Search Index ` in the Atlas manual. diff --git a/source/index.txt b/source/index.txt index 95be5811..e327bab5 100644 --- a/source/index.txt +++ b/source/index.txt @@ -1,3 +1,5 @@ +.. _csharp-index: + ================= MongoDB C# Driver ================= @@ -12,136 +14,127 @@ MongoDB C# Driver .. toctree:: - Previous Versions - Quick Start - Quick Reference - What's New - Usage Examples - Fundamentals - API Documentation <{+new-api-root+}/index.html> - FAQ - Connection Troubleshooting + Get Started + Connect + Databases & Collections + CRUD Operations + Aggregation + Indexes + Run a Database Command + Atlas Search + Atlas Vector Search + Time Series + Logging and Monitoring + Security + Serialization + Document Formats + Integrations + Reference + API Documentation <{+api-root+}> Issues & Help - Compatibility - Upgrade - Entity Framework Provider - {+analyzer-short+} -Introduction ------------- +Overview +-------- Welcome to the documentation site for the official {+driver-long+}. You can add the driver to your application to work with MongoDB in {+language+}. -Download the driver using `NuGet `__, or set up a runnable -project by following our :ref:`Quick Start guide `. -Previous Versions ------------------ +Get Started +----------- -For documentation on versions of the driver v2.18 and earlier, see the :ref:`csharp-previous-versions` section. +Learn how to install the driver, establish a connection to MongoDB, and begin +working with data in the :ref:`csharp-get-started` tutorial. -Connect to a Compatible MongoDB Deployment ------------------------------------------- +Connect to MongoDB +------------------ -You can use the {+driver-short+} to connect to MongoDB -deployments running on one of the following hosted services or editions: +Learn how to create and configure a connection to a MongoDB deployment +in the :ref:`csharp-connect` section. -.. include:: /includes/fact-environments.rst +Databases and Collections +------------------------- -Quick Start ------------ +Learn how to use the {+driver-short+} to work with MongoDB databases and collections +in the :ref:`csharp-databases-collections` section. + +Read and Write Data +------------------- -Learn how to establish a connection to MongoDB Atlas and begin -working with data in the :ref:`csharp-quickstart` section. +Learn how to find, update, and delete data in the :ref:`csharp-crud` section. -Quick Reference ---------------- +Transform Your Data with Aggregation +------------------------------------ -See driver syntax examples for common MongoDB commands in the -:ref:`Quick Reference ` section. +Learn how to use the {+driver-short+} to perform aggregation operations in the +:ref:`csharp-aggregation` section. -What's New ----------- +Optimize Queries with Indexes +----------------------------- -For a list of new features and changes in each version, see the :ref:`What's New ` +Learn how to work with common types of indexes in the :ref:`csharp-indexes` section. -Usage Examples --------------- +Run a Database Command +---------------------- -For fully runnable code snippets and explanations for common -methods, see :ref:`csharp-usage-examples`. +Learn how to run a database command in the :ref:`csharp-run-command` section. -Fundamentals +Atlas Search ------------ -For detailed information on key concepts of using the {+driver-short+}, see -:ref:`csharp-fundamentals`. - -API Documentation ------------------ - -For detailed information about types and methods in the {+driver-short+}, see -the `{+driver-long+} API documentation -<{+new-api-root+}/index.html>`__. - -Take the Free Online Course Taught by MongoDB ---------------------------------------------- +Learn how to use Atlas Search to build full-text search capabilities in the +:ref:`csharp-atlas-search` section. -.. list-table:: +Atlas Vector Search +------------------- - * - .. figure:: /includes/figures/M220N.png - :alt: Banner for the C# MongoDB University Course +Learn how to use Atlas Vector Search to query your Atlas data based on semantic meaning +rather than keyword matches in the +`Atlas Vector Search `__ +documentation. - - `Using MongoDB with C# `__ +Time Series +----------- - Learn the essentials of C# & ASP.NET application development with MongoDB. +Learn how to work with time series collections in the :ref:`csharp-time-series` section. -FAQ ---- +Logging and Monitoring +---------------------- -For answers to commonly asked questions about the {+driver-long+}, see the :ref:`csharp-faq` -section. +Learn how to monitor changes to your application and write them to logs in the +:ref:`csharp-logging-monitoring` section. -Connection Troubleshooting --------------------------- +Secure Your Data +---------------- -For solutions to issues you might encounter when using the driver to connect to -a MongoDB deployment, see the :ref:`csharp-connection-troubleshooting` section. +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`csharp-security` section. -Issues & Help +Serialization ------------- -Learn how to report bugs, contribute to the driver, and find -additional resources for asking questions in the :ref:`csharp-issues-help` section. +Learn how to serialize and deserialize data in the :ref:`csharp-serialization` section. -Compatibility -------------- - -For the compatibility charts that show the recommended {+driver-short+} version -for each {+mdb-server+} version, see :ref:`csharp-compatibility-tables`. +Document Formats +---------------- -Upgrade Driver Versions ------------------------ +Learn about different notations you can use to read and write data in the :ref:`csharp-document-formats` section. -Learn what changes you may need to make to your application to upgrade -driver versions in the :ref:`Upgrade Driver Versions ` -section. +Reference +--------- -Entity Framework Provider -------------------------- +Find more information about {+driver-short+} versions, compatibility, and upgrading driver +versions in the :ref:`csharp-reference` section. -The MongoDB Entity Framework Provider is an object-relational mapper (ORM) that lets you -use Microsoft's Entity Framework to work with MongoDB data. ORMs provide an -object-oriented interface for data management. +API Documentation +----------------- -To learn more, see the -`MongoDB Entity Framework Provider documentation `__. +For detailed information about types and methods in the {+driver-short+}, see +the `{+driver-long+} API documentation +<{+new-api-root+}/index.html>`__. -{+analyzer+} -------------------- +Issues & Help +------------- -The {+analyzer-short+} is a tool that helps you understand how your -{+driver-short+} code translates into the {+query-api+} and if your code -includes any unsupported LINQ or builder expressions. To learn more, see the -`{+analyzer-short+} documentation `__. +Learn how to report bugs, contribute to the driver, and find help in the +:ref:`` section. \ No newline at end of file diff --git a/source/fundamentals/indexes.txt b/source/indexes.txt similarity index 85% rename from source/fundamentals/indexes.txt rename to source/indexes.txt index 37288906..07f4420a 100644 --- a/source/fundamentals/indexes.txt +++ b/source/indexes.txt @@ -1,8 +1,8 @@ .. _csharp-indexes: -======= -Indexes -======= +========================= +Create and Manage Indexes +========================= .. facet:: :name: genre @@ -19,8 +19,10 @@ Indexes :class: singlecol .. toctree:: + :titlesonly: + :maxdepth: 1 - Atlas Search & Vector Search Indexes + Atlas Vector and Vector Search Indexes Overview -------- @@ -75,14 +77,25 @@ Index Types ----------- MongoDB provides several different index types to support querying -your data. The following sections describe the most common index types +your data. The following steps describe the process for creating an index: + +1. Use the ``IndexKeysDefinitionBuilder`` class, which you can access through the + ``Builders.IndexKeys`` property, to create one or more + ``IndexKeysDefinition`` objects. These key definitions describe the type + of index to create and the index's other properties. +#. Create a new ``CreateIndexModel`` object. Pass the key definitions from the + previous step to the constructor. +#. Call the ``CreateOne()`` method on your collection's ``Indexes`` property. Pass + the ``CreateIndexModel`` object from the previous step. + +The following sections describe the most common index types and provide sample code for creating each index type. .. note:: - These example uses the ``sample_mflix.movies`` and ``sample_mflix.theaters`` collections + The examples on this page use the ``sample_mflix.movies`` and ``sample_mflix.theaters`` collections from the :atlas:`Atlas sample datasets `. To learn how to create a - free MongoDB Atlas cluster and load the sample datasets, see :ref:`csharp-quickstart`. + free MongoDB Atlas cluster and load the sample datasets, see :ref:`csharp-get-started`. Single Field Indexes ~~~~~~~~~~~~~~~~~~~~ @@ -179,8 +192,7 @@ Clustered Indexes To create a clustered index, specify the clustered index option with the ``_id`` field as the key and the ``Unique`` property as ``true`` when you create your collection. A collection can only contain a single clustered -index. If you want to create a clustered index, then it must be specified when you create -a collection. +index. To create a clustered index, specify it when you create a collection. The following example creates a clustered index on the ``_id`` field while creating a new ``sample_mflix.reviews`` collection: @@ -244,7 +256,7 @@ The following query uses the text index created in the preceding code snippet: Multiple Fields +++++++++++++++ -A collection can only contain one text index. If you want to create a +A collection can only contain one text index. To create a text index for multiple text fields, you must create a compound index. A text search runs on all the text fields within the compound index. @@ -267,9 +279,15 @@ and :manual:`Text Indexes ` in the Server manual. Geospatial Indexes ~~~~~~~~~~~~~~~~~~ -MongoDB supports queries of geospatial coordinate data using **2dsphere -indexes**. With a 2dsphere index, you can query the geospatial data for -inclusion, intersection, and proximity. +You can query geospatial coordinate data in MongoDB by using **2d** or +**2dsphere indexes**. + +2dsphere Indexes +++++++++++++++++ + +2dsphere indexes support geospatial queries on an earth-like sphere. By using a 2dsphere +index, you can query the geospatial data For inclusion, intersection, and proximity. +The indexed field must be either GeoJSON objects or legacy coordinate pairs. To create a 2dsphere index, you must specify a field that contains only **GeoJSON objects**. For more details about this type, see :manual:`GeoJSON objects ` @@ -321,8 +339,12 @@ The following is an example of a geospatial query using the "location.geo" index :end-before: end-geospatial-query :dedent: -MongoDB also supports ``2d`` indexes for calculating distances on a Euclidean plane and -for working with the "legacy coordinate pairs" syntax. +2d Indexes +++++++++++ + +The {+driver-short+} also includes a ``Geo2D`` method for creating 2d indexes. +You can use these indexes to calculate distances on a Euclidean plane and +to work with the "legacy coordinate pairs" syntax used in MongoDB 2.2 and earlier. To learn more, see :manual:`Geospatial Queries ` in the Server manual. Unique Indexes @@ -386,3 +408,13 @@ all indexes in a collection: :start-after: begin-list-indexes :end-before: end-list-indexes :dedent: + +Additional Information +---------------------- + +For more information about the classes and methods used on this page, see the following +API documentation: + +- `CreateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoIndexManager-1.CreateOne.html>`__ +- `CreateIndexModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CreateIndexModel-1.html>`__ +- `IndexKeysDefinitionBuilder <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IndexKeysDefinitionBuilder-1.html>`__ \ No newline at end of file diff --git a/source/fundamentals/indexes/search-indexes.txt b/source/indexes/search-indexes.txt similarity index 100% rename from source/fundamentals/indexes/search-indexes.txt rename to source/indexes/search-indexes.txt diff --git a/source/integrations.txt b/source/integrations.txt new file mode 100644 index 00000000..65fe78ad --- /dev/null +++ b/source/integrations.txt @@ -0,0 +1,62 @@ +.. _csharp-integrations: + +====================== +Integrations and Tools +====================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn about {+driver-short+} integrations and tools. + :keywords: third-party + +.. toctree:: + :maxdepth: 1 + + OData + Entity Framework Provider + {+analyzer-short+} + +OData +----- + +OData (Open Data Protocol) is a standardized protocol for building and consuming +RESTful APIs that allows for the querying and manipulation of data by using +HTTP requests. It provides a uniform way to expose and interact +with data from multiple sources. + +To learn how to integrate OData with your MongoDB application, see the +:ref:`OData ` tutorial. + +Entity Framework Provider +------------------------- + +The MongoDB Entity Framework Provider is an object-relational mapper (ORM) that lets you +use Microsoft's Entity Framework to work with MongoDB data. ORMs provide an +object-oriented interface for data management. + +The provider includes features such as the following: + +- Intelligent object tracking +- Entity-based LINQ operations +- Entity Framework modeling and mapping with the fluent API +- Automatic database updates through change tracking + +To learn more, see the +`MongoDB Entity Framework Provider documentation `__. + +{+analyzer+} +------------------- + +The {+analyzer-short+} is a tool that helps you understand how your +{+driver-short+} code translates into the {+query-api+} and if your code +includes any unsupported LINQ or builder expressions. To learn more, see the +`{+analyzer-short+} documentation `__. \ No newline at end of file diff --git a/source/fundamentals/odata.txt b/source/integrations/odata.txt similarity index 99% rename from source/fundamentals/odata.txt rename to source/integrations/odata.txt index 7154b581..ede2c4cd 100644 --- a/source/fundamentals/odata.txt +++ b/source/integrations/odata.txt @@ -32,7 +32,7 @@ Sample Data This tutorial uses the ``sample_restaurants.restaurants`` collection from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. Tutorial -------- diff --git a/source/logging-and-monitoring.txt b/source/logging-and-monitoring.txt new file mode 100644 index 00000000..f459fe79 --- /dev/null +++ b/source/logging-and-monitoring.txt @@ -0,0 +1,18 @@ +.. _csharp-logging-monitoring: + +====================== +Logging and Monitoring +====================== + +.. facet:: + :name: programming_language + :values: csharp + +.. meta:: + :keywords: dotnet + +.. toctree:: + + Logging + Monitoring + Change Streams \ No newline at end of file diff --git a/source/fundamentals/crud/read-operations/change-streams.txt b/source/logging-and-monitoring/change-streams.txt similarity index 98% rename from source/fundamentals/crud/read-operations/change-streams.txt rename to source/logging-and-monitoring/change-streams.txt index 018cbff2..0b6a14f5 100644 --- a/source/fundamentals/crud/read-operations/change-streams.txt +++ b/source/logging-and-monitoring/change-streams.txt @@ -30,7 +30,7 @@ Sample Data The examples in this guide use the ``sample_restaurants.restaurants`` collection from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. The examples on this page use the following ``Restaurant``, ``Address``, and ``GradeEntry`` classes as models: @@ -295,11 +295,19 @@ of ``Watch()`` and ``WatchAsync()``: or ``WatchAsync()`` uses the default batch size. * - ``Collation`` - - | Specifies the collation to use for the change stream cursor. + - | Specifies the collation to use for the change stream cursor. See the + :ref:`` section of this page for more information. * - ``Comment`` - | Attaches a comment to the operation. +.. _csharp-change-stream-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + .. _csharp-change-stream-pre-post-image: Include Pre-Images and Post-Images diff --git a/source/fundamentals/logging.txt b/source/logging-and-monitoring/logging.txt similarity index 100% rename from source/fundamentals/logging.txt rename to source/logging-and-monitoring/logging.txt diff --git a/source/fundamentals/monitoring.txt b/source/logging-and-monitoring/monitoring.txt similarity index 100% rename from source/fundamentals/monitoring.txt rename to source/logging-and-monitoring/monitoring.txt diff --git a/source/quick-start.txt b/source/quick-start.txt deleted file mode 100644 index f56110bd..00000000 --- a/source/quick-start.txt +++ /dev/null @@ -1,135 +0,0 @@ -.. _csharp-quickstart: - -=========== -Quick Start -=========== - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: set up, runnable app, initialize, connect - :description: Connect your .NET application to a MongoDB Atlas cluster using the .NET/C# Driver, and run queries on sample data. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. include:: /includes/quick-start/overview.rst - -Create a MongoDB Cluster ------------------------- - -Set Up a Free Tier Cluster in Atlas -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To set up your Atlas Free Tier Cluster required for this guide, complete the guide on -:guides:`MongoDB Atlas Setup `. - -After completing the steps in the Atlas guide, you have a new MongoDB -cluster deployed in Atlas, a new database user, and -:atlas:`sample datasets loaded ` into your cluster. You also have -a connection string similar to the following in your copy buffer: - -.. code-block:: bash - - "mongodb+srv://:@cluster0.abc.mongodb.net/?retryWrites=true&w=majority" - -Set Your Connection String -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Run the following code at the command prompt to save your MongoDB -:ref:`connection string ` to an -environment variable. This method is safer than including your credentials in your source -code. - -.. code-block:: bash - - export MONGODB_URI="" - -.. note:: PowerShell Environment Variables - - If you are using Microsoft PowerShell, run the following command to - save your connection string in an environment variable: - - .. code-block:: bash - - set MONGODB_URI="" - -.. important:: - - Make sure to replace the ```` and ```` sections of the connection - string with the username and password of your Atlas database user. - -For more information about connection strings, see :manual:`Connection Strings `. - -Set Up Your Project -------------------- - -Create the Project -~~~~~~~~~~~~~~~~~~ - -Create a new directory and initialize your project with the ``dotnet new`` command, as follows: - -.. code-block:: shell - - mkdir csharp-quickstart - cd csharp-quickstart - dotnet new console - -.. _csharp-add-mongodb-dependency: - -Add MongoDB as a Dependency -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Use the ``dotnet add`` command to add the {+driver-short+} to your project as a dependency. - -.. code-block:: shell - - dotnet add package MongoDB.Driver - -Query Your MongoDB Cluster from Your Application ------------------------------------------------- - -In this step, you'll use the {+driver-short+} -to connect to your MongoDB cluster and run a query on the sample data. You'll need your -preferred text editor or :wikipedia:`integrated development environment (IDE) ` -installed and running. - -Open the file named ``Program.cs`` in the base directory of your project. Copy the -following sample code into ``Program.cs`` - -.. literalinclude:: /includes/quick-start/Program.cs - :language: csharp - :dedent: - -This sample code runs a query against your sample dataset in MongoDB Atlas. Run it -from your command line by using the following command: - -.. code-block:: bash - - dotnet run csharp-quickstart.csproj - -.. include:: /includes/quick-start/query-output.rst - -.. tip:: - - If your output is empty, ensure you have loaded the - :atlas:`sample datasets ` into your cluster. - -After completing this step, you should have a working application that uses -the {+driver-short+} to connect to your MongoDB cluster, run a query on the -sample data, and print out the result. - -To learn more about connecting to Atlas with the {+driver-short+}, see -the :atlas:`Atlas driver connection ` guide -and select :guilabel:`{+language+}` from the :guilabel:`Select your language` dropdown. - -Next steps ----------- - -Learn how to read and modify data using the {+driver-short+} in the CRUD Operations -guide or how to perform common operations in Usage Examples. diff --git a/source/reference.txt b/source/reference.txt new file mode 100644 index 00000000..d1d5e55b --- /dev/null +++ b/source/reference.txt @@ -0,0 +1,25 @@ +.. _csharp-reference: + +========= +Reference +========= + +.. facet:: + :name: programming_language + :values: csharp + +.. meta:: + :keywords: dotnet + +.. toctree:: + + Quick Reference + Release Notes + Compatibility + Upgrade + Versions 2.0 to 2.18 + +Previous Versions +----------------- + +For documentation on versions of the driver v2.18 and earlier, see the :ref:`csharp-previous-versions` section. \ No newline at end of file diff --git a/source/compatibility.txt b/source/reference/compatibility.txt similarity index 87% rename from source/compatibility.txt rename to source/reference/compatibility.txt index 935ebcc8..cfa70d77 100644 --- a/source/compatibility.txt +++ b/source/reference/compatibility.txt @@ -42,5 +42,5 @@ The first column lists the driver version. .. include:: /includes/language-compatibility-table-csharp.rst -For more information on how to read the compatibility tables, see our guide on -:ref:`MongoDB Compatibility Tables. ` +For more information about how to read the compatibility tables, see +`MongoDB Compatibility Tables `__. diff --git a/source/previous-versions.txt b/source/reference/previous-versions.txt similarity index 96% rename from source/previous-versions.txt rename to source/reference/previous-versions.txt index 33b0af5d..65a4b025 100644 --- a/source/previous-versions.txt +++ b/source/reference/previous-versions.txt @@ -1,8 +1,8 @@ .. _csharp-previous-versions: -================= -Previous Versions -================= +==================== +Versions 2.0 to 2.18 +==================== .. meta:: :description: Access documentation for previous versions of the C# driver, including versions 2.0 through 2.18. diff --git a/source/quick-reference.txt b/source/reference/quick-reference.txt similarity index 94% rename from source/quick-reference.txt rename to source/reference/quick-reference.txt index 75c9113d..3d4b183a 100644 --- a/source/quick-reference.txt +++ b/source/reference/quick-reference.txt @@ -26,7 +26,6 @@ their related reference and API documentation. * - | **Find a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. io-code-block:: @@ -50,7 +49,6 @@ their related reference and API documentation. * - | **Find a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.FindAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. io-code-block:: @@ -75,7 +73,6 @@ their related reference and API documentation. * - | **Find Multiple Documents** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. io-code-block:: @@ -103,7 +100,6 @@ their related reference and API documentation. * - | **Find Multiple Documents (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. io-code-block:: @@ -131,7 +127,6 @@ their related reference and API documentation. * - | **Insert a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertOne.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -142,7 +137,6 @@ their related reference and API documentation. * - | **Insert a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertOneAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -153,7 +147,6 @@ their related reference and API documentation. * - | **Insert Multiple Documents** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertMany.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -168,7 +161,6 @@ their related reference and API documentation. * - | **Insert Multiple Documents (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertManyAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -183,7 +175,6 @@ their related reference and API documentation. * - | **Update a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -200,7 +191,6 @@ their related reference and API documentation. * - | **Update a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOneAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -217,7 +207,6 @@ their related reference and API documentation. * - | **Update Multiple Documents** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -234,7 +223,6 @@ their related reference and API documentation. * - | **Update Multiple Documents (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -273,7 +261,6 @@ their related reference and API documentation. * - | **Replace a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -306,7 +293,6 @@ their related reference and API documentation. * - | **Replace a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -339,7 +325,6 @@ their related reference and API documentation. * - | **Delete a Document** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteOne.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -353,7 +338,6 @@ their related reference and API documentation. * - | **Delete a Document (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteOneAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -367,7 +351,6 @@ their related reference and API documentation. * - | **Delete Multiple Documents** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteMany.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -381,7 +364,6 @@ their related reference and API documentation. * - | **Delete Multiple Documents (Async)** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteManyAsync.html>`__ - | :ref:`Usage Example ` | :ref:`Fundamentals ` - .. code-block:: csharp @@ -549,7 +531,7 @@ their related reference and API documentation. * - | **Project Document Fields When Retrieving Them** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ProjectionDefinitionBuilder-1.html>`__ - | :ref:`Fundamentals ` + | :ref:`Fundamentals ` - .. io-code-block:: :copyable: true @@ -582,7 +564,7 @@ their related reference and API documentation. * - | **Create an Index** | | `API Documentation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoIndexManager-1.CreateOne.html>`__ - | :ref:`Fundamentals ` + | :ref:`Fundamentals ` - .. code-block:: csharp :copyable: true diff --git a/source/whats-new.txt b/source/reference/release-notes.txt similarity index 97% rename from source/whats-new.txt rename to source/reference/release-notes.txt index 39a41557..c8e42642 100644 --- a/source/whats-new.txt +++ b/source/reference/release-notes.txt @@ -1,8 +1,9 @@ .. _csharp-whats-new: +.. _csharp-release-notes: -========== -What's New -========== +============= +Release Notes +============= .. contents:: On this page :local: @@ -132,8 +133,7 @@ The 3.3 driver release includes the following new features: - Adds support for :manual:`$elemMatch ` queries directly against values by providing an overload of the ``ElemMatch()`` method that takes only a filter parameter. To learn - more, see the :ref:`csharp-builders-array-operators` section of the - Builders guide. + more, see :ref:`csharp-update-one-arrays` and :ref:`csharp-update-many-arrays`. - Adds support for using the ``OfType()`` method and ``is`` operator to check the type of a scalar discriminator. @@ -231,9 +231,8 @@ The 3.1 driver release includes the following new features: - Adds a sort option for update and replace operations. This change allows you to set a sort order if multiple documents match your - filter when attempting to update or replace a single document. To - learn more, see the :ref:`csharp-update-one` and - :ref:`csharp-replace-operation` guides. + filter when attempting to update or replace a single document. To learn more, + see the :ref:`csharp-update-one` and :ref:`csharp-update-many` guides. For more information about this release, see the :github:`v3.1 release notes `. @@ -262,7 +261,7 @@ The 3.0 driver release includes the following new features: - The ``IMongoClient`` interface inherits the ``IDisposable`` interface. As a result, the ``MongoClient`` class and other classes that implement the ``IMongoClient`` interface - contain a ``Dispose()`` method, which disposes of the client. This method does not + contain a ``Disp- Adds support for the ``sort`` option to be passed to update commands.ose()`` method, which disposes of the client. This method does not dispose the underlying cluster and connections to the MongoDB server. To dispose of the cluster and connections, call the ``ClusterRegistry.UnregisterAndDisposeCluster()`` method. diff --git a/source/upgrade.txt b/source/reference/upgrade.txt similarity index 96% rename from source/upgrade.txt rename to source/reference/upgrade.txt index 6b74571c..3ddd8655 100644 --- a/source/upgrade.txt +++ b/source/reference/upgrade.txt @@ -22,8 +22,8 @@ Upgrade Driver Versions :titlesonly: :maxdepth: 1 - Version 2.x - Version 3.0 + Version 2.x + Version 3.0 Overview -------- diff --git a/source/upgrade/v2.txt b/source/reference/upgrade/v2.txt similarity index 100% rename from source/upgrade/v2.txt rename to source/reference/upgrade/v2.txt diff --git a/source/upgrade/v3.txt b/source/reference/upgrade/v3.txt similarity index 100% rename from source/upgrade/v3.txt rename to source/reference/upgrade/v3.txt diff --git a/source/fundamentals/databases-collections/run-command.txt b/source/run-command.txt similarity index 99% rename from source/fundamentals/databases-collections/run-command.txt rename to source/run-command.txt index 28312d91..a6fb0cdc 100644 --- a/source/fundamentals/databases-collections/run-command.txt +++ b/source/run-command.txt @@ -45,7 +45,7 @@ Sample Data The examples in this guide use the ``sample_restaurants.restaurants`` collection from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. +free MongoDB Atlas cluster and load the sample datasets, see the :ref:``. Execute a Command ----------------- diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 00000000..56e5458a --- /dev/null +++ b/source/security.txt @@ -0,0 +1,18 @@ +.. _csharp-security: + +======== +Security +======== + +.. facet:: + :name: programming_language + :values: csharp + +.. meta:: + :keywords: dotnet + +.. toctree:: + + Authentication + In-Use Encryption + TLS/SSL \ No newline at end of file diff --git a/source/fundamentals/authentication.txt b/source/security/authentication.txt similarity index 86% rename from source/fundamentals/authentication.txt rename to source/security/authentication.txt index b8c6853c..4aa8affc 100644 --- a/source/fundamentals/authentication.txt +++ b/source/security/authentication.txt @@ -21,12 +21,12 @@ Authentication Mechanisms .. toctree:: :caption: Authentication - SCRAM - X.509 - AWS IAM - OIDC - LDAP (PLAIN) - Kerberos (GSSAPI) + SCRAM + X.509 + AWS IAM + OIDC + LDAP (PLAIN) + Kerberos (GSSAPI) Overview -------- diff --git a/source/fundamentals/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt similarity index 98% rename from source/fundamentals/authentication/aws-iam.txt rename to source/security/authentication/aws-iam.txt index 1376ce81..cc6def81 100644 --- a/source/fundamentals/authentication/aws-iam.txt +++ b/source/security/authentication/aws-iam.txt @@ -1,9 +1,9 @@ .. _csharp-mongodb-aws: .. _csharp-authentication-aws: -================================== -AWS Identity and Access Management -================================== +====================== +AWS IAM Authentication +====================== .. contents:: On this page :local: diff --git a/source/fundamentals/authentication/kerberos.txt b/source/security/authentication/kerberos.txt similarity index 97% rename from source/fundamentals/authentication/kerberos.txt rename to source/security/authentication/kerberos.txt index 1c289266..5d166e50 100644 --- a/source/fundamentals/authentication/kerberos.txt +++ b/source/security/authentication/kerberos.txt @@ -1,9 +1,9 @@ .. _csharp-kerberos: .. _csharp-authentication-kerberos: -================= -Kerberos (GSSAPI) -================= +================================ +Kerberos (GSSAPI) Authentication +================================ .. contents:: On this page :local: @@ -76,7 +76,7 @@ see the corresponding syntax: - On Windows, the process owner running the application is the same as the user needing authentication. - - On Linux, the user has initialized their keytab via ``kinit username@REALM.COM``. + - On Linux, the user has initialized their keytab by using ``kinit username@REALM.COM``. Additional Properties ~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/fundamentals/authentication/ldap.txt b/source/security/authentication/ldap.txt similarity index 100% rename from source/fundamentals/authentication/ldap.txt rename to source/security/authentication/ldap.txt diff --git a/source/fundamentals/authentication/oidc.txt b/source/security/authentication/oidc.txt similarity index 98% rename from source/fundamentals/authentication/oidc.txt rename to source/security/authentication/oidc.txt index d9e85025..81cd766b 100644 --- a/source/fundamentals/authentication/oidc.txt +++ b/source/security/authentication/oidc.txt @@ -1,9 +1,9 @@ .. _csharp-mongodb-oidc: .. _csharp-authentication-oidc: -=================================== -OIDC (Workload Identity Federation) -=================================== +================================================== +OIDC (Workload Identity Federation) Authentication +================================================== .. contents:: On this page :local: diff --git a/source/fundamentals/authentication/scram.txt b/source/security/authentication/scram.txt similarity index 96% rename from source/fundamentals/authentication/scram.txt rename to source/security/authentication/scram.txt index 64d047ad..39a48ec8 100644 --- a/source/fundamentals/authentication/scram.txt +++ b/source/security/authentication/scram.txt @@ -1,8 +1,8 @@ .. _csharp-authentication-scram: -===== -SCRAM -===== +============================================ +SCRAM-SHA-1 and SCRAM-SHA-256 Authentication +============================================ .. contents:: On this page :local: diff --git a/source/fundamentals/authentication/x509.txt b/source/security/authentication/x509.txt similarity index 98% rename from source/fundamentals/authentication/x509.txt rename to source/security/authentication/x509.txt index 326245da..dc80bbce 100644 --- a/source/fundamentals/authentication/x509.txt +++ b/source/security/authentication/x509.txt @@ -1,8 +1,8 @@ .. _csharp-authentication-x509: -===== -X.509 -===== +============================= +X.509 Authentication with TLS +============================= .. contents:: On this page :local: diff --git a/source/fundamentals/encrypt-fields.txt b/source/security/in-use-encryption.txt similarity index 77% rename from source/fundamentals/encrypt-fields.txt rename to source/security/in-use-encryption.txt index f519dca0..1939074c 100644 --- a/source/fundamentals/encrypt-fields.txt +++ b/source/security/in-use-encryption.txt @@ -1,4 +1,5 @@ .. _csharp-fle: +.. _csharp-in-use-encryption: .. sharedinclude:: dbx/encrypt-fields.rst diff --git a/source/fundamentals/connection/tls.txt b/source/security/tls-ssl.txt similarity index 98% rename from source/fundamentals/connection/tls.txt rename to source/security/tls-ssl.txt index 2019cf98..a34cc5fd 100644 --- a/source/fundamentals/connection/tls.txt +++ b/source/security/tls-ssl.txt @@ -154,7 +154,7 @@ You can allow insecure TLS in two different ways: using a property on a Check Certificate Revocation ---------------------------- -When an X.509 certificate should no longer be trusted--for example, if its private key +When an X.509 certificate is no longer trusted--for example, if its private key has been compromised--the certificate authority will revoke the certificate. By default, the {+driver-short+} doesn't check whether a server's certificate has been @@ -208,7 +208,7 @@ Windows, macOS, and Linux: - :wikipedia:`Online Certificate Status Protocol (OCSP) `, a common mechanism for checking revocation - :wikipedia:`OCSP stapling `, a mechanism in which the server - includes a time-stamped OCSP response to the client along with the certificate + includes a time-stamped OCSP response to the client with the certificate - :wikipedia:`Certificate revocation lists (CRLs), `, an alternative to OCSP diff --git a/source/fundamentals/serialization.txt b/source/serialization.txt similarity index 83% rename from source/fundamentals/serialization.txt rename to source/serialization.txt index 26bf91ec..7e55fb58 100644 --- a/source/fundamentals/serialization.txt +++ b/source/serialization.txt @@ -17,14 +17,14 @@ Serialization :backlinks: none :depth: 2 :class: singlecol - + .. toctree:: - :caption: Serialization + :caption: Custom Types - Class Mapping - POCOs - Polymorphic Objects - GUIDs + Class Mapping + POCOs + Polymorphic Objects + GUIDs Overview -------- @@ -49,6 +49,48 @@ primitive types, collection types, and custom classes. For a full list of available serializers, see the `Serializers namespace API documentation <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Serializers.html>`__. +.. _csharp-faq-object-serializer: + +ObjectSerializer +---------------- + +The ``ObjectSerializer`` class allows serialization and deserialization only of types +that are considered safe. When you construct an ``ObjectSerializer``, +you can pass in a delegate of type ``Func``. This delegate +accepts an object type and returns a boolean value indicating whether the +type is safe for serialization. + +In most cases, pass in the ``ObjectSerializer.DefaultAllowedTypes()`` +delegate. This method returns true for several well-known +framework types that we have deemed safe. To serialize custom types, +create a boolean expression that evaluates to ``true`` for the +types you want to include. Then, add this expression to the end of the +delegate you pass to the ``ObjectSerializer`` constructor. + +In the following example, +the ``ObjectSerializer`` will serialize and deserialize any type that is allowed by +``ObjectSerializer.DefaultAllowedTypes()`` or whose full name begins with +``"MyNamespace"``: + +.. code-block:: csharp + + var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) + || type.FullName.StartsWith("MyNamespace")); + BsonSerializer.RegisterSerializer(objectSerializer); + +To allow anonymous types to be serialized, add the boolean expression +``type.FullName.StartsWith("<>f__AnonymousType"))`` to your delegate, +as shown in the following example: + +.. code-block:: csharp + + var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) + || type.FullName.StartsWith("<>f__AnonymousType")); + BsonSerializer.RegisterSerializer(objectSerializer); + +Create and register your ``ObjectSerializer`` at the start of your program, +before doing anything else. + Serializer Registry ------------------- @@ -261,10 +303,10 @@ represented in MongoDB: :ref:`csharp-atlas-vector-search` involves creating and querying large numerical arrays. If your application uses - {+vector-search+}, you might benefit from the performance + {+avs+}, you might benefit from the performance improvements from using ``Memory`` and ``ReadOnlyMemory`` to store array representations of embeddings and query vectors. To learn more, - see :ref:`csharp-supported-vector-types` in the {+vector-search+} guide. + see :ref:`csharp-supported-vector-types` in the {+avs+} guide. Additional Information ---------------------- diff --git a/source/fundamentals/serialization/class-mapping.txt b/source/serialization/class-mapping.txt similarity index 96% rename from source/fundamentals/serialization/class-mapping.txt rename to source/serialization/class-mapping.txt index 48f0d245..cd1e629f 100644 --- a/source/fundamentals/serialization/class-mapping.txt +++ b/source/serialization/class-mapping.txt @@ -21,8 +21,8 @@ Overview -------- In this guide, you can learn how to customize the way the {+driver-long+} -maps BSON documents to and from {+language+} classes. You can read this page -to learn more about the default class mapping behavior, or if you need to +maps BSON documents to and from {+language+} classes. Read this page +to learn more about the default class mapping behavior, or if you must customize the way the driver serializes or deserializes your data. You can also use POCO attributes to set serialization behavior. To learn @@ -38,7 +38,7 @@ the name of the field in the document to the name of the property in the class. .. important:: - The type of the property in your class should match the type of the field in + Match the type of the property in your class to the type of the field in the document. The {+driver-short+} instantiates a serializer based on the type of the property in your class. If the types don't match when the driver attempts to deserialize the data, the serializer throws an exception. @@ -75,7 +75,7 @@ class: .. important:: When to Register a Class Map You must register a class map *before* it's needed in your code. We recommend - registering class maps prior to initializing a connection with MongoDB. + registering class maps before initializing a connection with MongoDB. You can also manually map a subset of class properties, while still allowing the driver to automatically map the remaining properties. To do this, @@ -352,11 +352,11 @@ You can also support extra elements when initializing a class map as follows: Dynamically Serialize Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can use a method to determine whether or not to serialize a property. For +You can use a method to determine whether to serialize a property. For the driver to automatically use the method when serializing, you must prefix the method name with ``ShouldSerialize`` followed by the name of the property that the method applies to. When the driver sees a method with this naming -convention, it uses that method to determine whether or not to serialize +convention, it uses that method to determine whether to serialize properties that have the provided property name. The following example creates a method that only serializes the ``Age`` property diff --git a/source/fundamentals/serialization/guid-serialization.txt b/source/serialization/guids.txt similarity index 100% rename from source/fundamentals/serialization/guid-serialization.txt rename to source/serialization/guids.txt diff --git a/source/fundamentals/serialization/poco.txt b/source/serialization/poco.txt similarity index 98% rename from source/fundamentals/serialization/poco.txt rename to source/serialization/poco.txt index 90be6d19..b165356a 100644 --- a/source/fundamentals/serialization/poco.txt +++ b/source/serialization/poco.txt @@ -28,8 +28,8 @@ features from any framework-specific base classes or interfaces. We recommend using POCOs in your {+language+} code to adhere to idiomatic driver usage and achieve the best performance. -You should read this guide if you want to learn more about how to use -POCOs with the {+driver-short+} or if you need to adjust the driver's default +Read this guide if you want to learn more about how to use +POCOs with the {+driver-short+} or if you must adjust the driver's default field mapping behavior. Create a POCO @@ -85,8 +85,7 @@ Custom Serialization If the default field mapping behavior does not meet your needs, you can specify custom behavior using serialization-related attributes. These attributes change the way that the driver serializes each property of -your POCO. This section describes some of the common -serialization-related attributes. +your POCO. This section describes some common serialization-related attributes. Serialize Read-Only Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -791,7 +790,7 @@ serialization-related attributes: - ``[BsonDateTimeOptions(DateOnly = true)]``, which specifies that the ``DateTime`` property represents only a date value, with no associated time -.. literalinclude:: ../../includes/fundamentals/code-examples/Clothing.cs +.. literalinclude:: /includes/fundamentals/code-examples/Clothing.cs :start-after: start-model :end-before: end-model :language: csharp @@ -844,9 +843,6 @@ Additional Information For a full list of serialization-related attributes, see the `Serialization.Attributes API documentation <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Attributes.html>`__. -For additional read and write operation examples using POCOs, see the :ref:`Usage Examples -` or the :ref:`CRUD Fundamentals Pages `. - To learn more about how the driver maps BSON documents to POCOs, see :ref:`csharp-class-mapping`. diff --git a/source/fundamentals/serialization/polymorphic-objects.txt b/source/serialization/polymorphic-objects.txt similarity index 100% rename from source/fundamentals/serialization/polymorphic-objects.txt rename to source/serialization/polymorphic-objects.txt diff --git a/source/fundamentals/time-series.txt b/source/time-series.txt similarity index 99% rename from source/fundamentals/time-series.txt rename to source/time-series.txt index c4238f67..0b0c35e5 100644 --- a/source/fundamentals/time-series.txt +++ b/source/time-series.txt @@ -93,7 +93,7 @@ Query a Time Series Collection ------------------------------ To query a time series collection, follow the conventions for retrieving and aggregating -data. For more information about these conventions, see the :ref:`csharp-retrieve` and +data. For more information about these conventions, see the :ref:`csharp-find` and :ref:`csharp-aggregation` guides. Additional Information diff --git a/source/usage-examples.txt b/source/usage-examples.txt deleted file mode 100644 index 43669717..00000000 --- a/source/usage-examples.txt +++ /dev/null @@ -1,106 +0,0 @@ -.. _csharp-usage-examples: - -============== -Usage Examples -============== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code, .NET, operation - :description: Explore C# usage examples for MongoDB operations, including synchronous and asynchronous code snippets, using sample datasets and custom serialization. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -.. toctree:: - - Find a Document - Find Multiple Documents - Insert a Document - Insert Multiple Documents - Update a Document - Update Many Documents - Replace a Document - Delete a Document - Delete Many Documents - -Overview --------- - -Usage examples provide convenient starting points for popular MongoDB -operations. Each example provides the following information: - -- A code snippet that shows how to perform the operation in synchronous and - asynchronous frameworks - -- A link to a fully runnable console application using the operation - -- The expected result after running the example - -.. tip:: - - Whether you use a synchronous or asynchronous framework in your application depends - on your use case. Synchronous calls are more suitable for simple query workflows or - when you must implement sequential logic. Consider using asynchronous calls if - your application relies on multiple concurrent database requests or if your - program doesn't require an immediate response from the database to continue - executing. - - We encourage experimenting with both approaches to determine the most - suitable framework for your purposes. - -How to Use the Usage Examples ------------------------------ - -These examples use the :atlas:`sample datasets ` -provided by Atlas. You can load them into your database on the free tier of -MongoDB Atlas by following the -:atlas:`Get Started with Atlas Guide ` -or you can -:guides:`import the sample dataset into a local MongoDB instance -`. - -Once you have imported the dataset, you can copy and paste a usage -example into your development environment of choice. You can follow the -:ref:`csharp-quickstart` to learn more about getting -started with the {+driver-long+}. Once you've copied a usage example, -you'll need to edit the connection URI to get the example connected to -your MongoDB instance: - -.. code-block:: csharp - - // Replace the following with your MongoDB deployment's connection string. - private static string _mongoConnectionString = ""; - -For more information about connecting to your MongoDB instance, see the -:ref:`Connection Guide `. - -Example Classes ---------------- - -The usage examples in this section show how to perform operations on documents -in the ``restaurants`` collection. The examples use the following ``Restaurant``, -``Address``, and ``GradeEntry`` classes to model the data in this collection: - -.. literalinclude:: /includes/code-examples/Restaurant.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/Address.cs - :language: csharp - :copyable: - :dedent: - -.. literalinclude:: /includes/code-examples/GradeEntry.cs - :language: csharp - :copyable: - :dedent: - -.. include:: /includes/convention-pack-note.rst diff --git a/source/usage-examples/deleteMany.txt b/source/usage-examples/deleteMany.txt deleted file mode 100644 index d2d16dbc..00000000 --- a/source/usage-examples/deleteMany.txt +++ /dev/null @@ -1,83 +0,0 @@ -.. _csharp-delete-many: - -===================== -Delete Many Documents -===================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Delete multiple documents in a collection using the `DeleteMany()` or `DeleteManyAsync()` methods in C#. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can delete more than one document using the ``DeleteMany()`` synchronous -method or the ``DeleteManyAsync()`` asynchronous method on a collection object. - -Example -------- - -The following code deletes all documents in the ``restaurants`` collection whose -``borough`` field value equals the word "Brooklyn". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding -code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: delete-many-sync - - .. literalinclude:: ../includes/code-examples/delete-many/DeleteMany.cs - :start-after: start-delete-many-builders - :end-before: end-delete-many-builders - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``DeleteMany()`` operation, see the - `DeleteMany code sample <{+example+}/delete-many/DeleteMany.cs>`__. - - .. tab:: Asynchronous - :tabid: delete-many-async - - .. literalinclude:: ../includes/code-examples/delete-many/DeleteManyAsync.cs - :start-after: start-delete-many-async - :end-before: end-delete-many-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``DeleteManyAsync()`` operation, see the - `DeleteManyAsync code sample <{+example+}/delete-many/DeleteManyAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running either of the preceding full examples prints the following results: - -.. code-block:: none - - Deleting documents... - Deleted documents: 6086 - Resetting sample data...done. - -Additional Information ----------------------- - -To learn more about deleting documents, see the :ref:`csharp-delete-guide` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -* `DeleteMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteMany.html>`__ -* `DeleteManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteManyAsync.html>`__ diff --git a/source/usage-examples/deleteOne.txt b/source/usage-examples/deleteOne.txt deleted file mode 100644 index 5dcfac68..00000000 --- a/source/usage-examples/deleteOne.txt +++ /dev/null @@ -1,92 +0,0 @@ -.. _csharp-delete-one: - -================= -Delete a Document -================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Learn how to delete a document from a collection using the synchronous `DeleteOne()` or asynchronous `DeleteOneAsync()` methods in C#. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can delete a document from a collection by using the synchronous -``DeleteOne()`` method, or the asynchronous ``DeleteOneAsync()`` method. - -.. note:: - - The ``DeleteOne()`` method deletes only the first document that matches the filter. - To delete more than one document, use the ``DeleteMany()`` method. - - To learn more about using ``DeleteMany()``, see :ref:`csharp-delete-many`. - -Example -------- - -Delete a Document by Using Builders -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example uses ``Builders`` to delete a document in -the ``restaurants`` collection with the ``name`` "Ready Penny Inn". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: builders-sync - - .. literalinclude:: ../includes/code-examples/delete-one/DeleteOne.cs - :start-after: start-delete-one-builders - :end-before: end-delete-one-builders - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``DeleteOne()`` method, see the - `Synchronous Delete One Example <{+example+}/delete-one/DeleteOne.cs>`__ - - .. tab:: Asynchronous - :tabid: builders-async - - .. literalinclude:: ../includes/code-examples/delete-one/DeleteOneAsync.cs - :start-after: start-delete-one-builders-async - :end-before: end-delete-one-builders-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``DeleteOne()`` method, see the - `Asynchronous Delete One Example <{+example+}/delete-one/DeleteOneAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running either of the preceding full examples prints the following results: - -.. code-block:: none - - Deleting a document with builders... - Deleted documents: 1 - -Additional Information ----------------------- - -To learn more about deleting documents, see the :ref:`csharp-delete-guide` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -- `DeleteOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteOne.html>`__ -- `DeleteOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.DeleteOneAsync.html>`__ \ No newline at end of file diff --git a/source/usage-examples/facets.toml b/source/usage-examples/facets.toml deleted file mode 100644 index 07bd7b7f..00000000 --- a/source/usage-examples/facets.toml +++ /dev/null @@ -1,3 +0,0 @@ -[[facets]] -category = "genre" -value = "tutorial" diff --git a/source/usage-examples/findMany.txt b/source/usage-examples/findMany.txt deleted file mode 100644 index ab07a068..00000000 --- a/source/usage-examples/findMany.txt +++ /dev/null @@ -1,179 +0,0 @@ -.. _csharp-find-multiple: - -======================= -Find Multiple Documents -======================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Retrieve multiple documents from a collection using the `Find()` method in C# with examples for both asynchronous and synchronous operations. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can retrieve multiple documents from a collection by using the -``Find()`` method. - -Example -------- - -Find Documents by Using Builders -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example uses ``Builders`` to find documents in -the ``restaurants`` collection with the ``cuisine`` "Pizza". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: builders-sync - - .. literalinclude:: ../includes/code-examples/find-many/FindMany.cs - :start-after: start-find-builders-sync - :end-before: end-find-builders-sync - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to synchronously - find multiple documents, see - `Synchronous Find Multiple Example <{+example+}/find-many/FindMany.cs>`__. - - .. tab:: Asynchronous - :tabid: builders-async - - .. literalinclude:: ../includes/code-examples/find-many/FindManyAsync.cs - :start-after: start-find-builders-async - :end-before: end-find-builders-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to asynchronously - find multiple documents, see - `Asynchronous Find Multiple Example <{+example+}/find-many/FindManyAsync.cs>`__. - -Find Documents by Using LINQ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example uses LINQ to find documents in the -``restaurants`` collection with the ``cuisine`` "Pizza". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: linq-sync - - .. literalinclude:: ../includes/code-examples/find-many/FindMany.cs - :start-after: start-find-linq-sync - :end-before: end-find-linq-sync - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to synchronously - find multiple documents, see - `Synchronous Find Multiple Example <{+example+}/find-many/FindMany.cs>`__. - - .. tab:: Asynchronous - :tabid: linq-async - - .. literalinclude:: ../includes/code-examples/find-many/FindManyAsync.cs - :start-after: start-find-linq-async - :end-before: end-find-linq-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to asynchronously - find multiple documents, see - `Asynchronous Find Multiple Example <{+example+}/find-many/FindManyAsync.cs>`__. - -.. _csharp_find_all: - -Find All Documents -~~~~~~~~~~~~~~~~~~ - -The following example finds all documents in the ``restaurants`` collection. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: find-all-sync - - .. literalinclude:: ../includes/code-examples/find-many/FindMany.cs - :start-after: start-find-all-sync - :end-before: end-find-all-sync - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to synchronously - find multiple documents, see - `Synchronous Find Multiple Example <{+example+}/find-many/FindMany.cs>`__. - - .. tab:: Asynchronous - :tabid: find-all-async - - .. literalinclude:: ../includes/code-examples/find-many/FindManyAsync.cs - :start-after: start-find-all-async - :end-before: end-find-all-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method to asynchronously - find multiple documents, see - `Asynchronous Find Multiple Example <{+example+}/find-many/FindManyAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running the preceding full examples prints the following results: - -.. code-block:: none - - Finding documents with builders...: - Number of documents found: 1163 - - Finding documents with LINQ...: - Number of documents found: 1163 - - Finding all documents...: - Number of documents found: 25359 - -.. tip:: Sample Datasets - - These examples use the :atlas:`sample datasets ` provided by Atlas. - The number of documents returned may differ depending on the data in your - collection. - -Additional Information ----------------------- - -To learn more about retrieving documents, see the :ref:`csharp-retrieve` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -To learn how to find documents using LINQ, see :ref:`csharp-linq`. - -API Documentation ------------------ - -- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ \ No newline at end of file diff --git a/source/usage-examples/findOne.txt b/source/usage-examples/findOne.txt deleted file mode 100644 index 3b167dfa..00000000 --- a/source/usage-examples/findOne.txt +++ /dev/null @@ -1,133 +0,0 @@ -.. _csharp-find-one: - -=============== -Find a Document -=============== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Retrieve a document from a collection using the `Find()` method in C# with examples for both asynchronous and synchronous operations. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can retrieve a document by using the ``Find()`` method on a collection object. - -Example -------- - -Find a Document by Using Builders -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example uses ``Builders`` to find a document in the ``restaurants`` -collection that has a ``name`` field with a value of "Bagels N Buns". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: builders-sync - - .. literalinclude:: ../includes/code-examples/find-one/FindOne.cs - :start-after: start-find-builders - :end-before: end-find-builders - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method - to synchronously find one document, see the `Synchronous Find One Example - <{+example+}/find-one/FindOne.cs>`__. - - .. tab:: Asynchronous - :tabid: builders-async - - .. literalinclude:: ../includes/code-examples/find-one/FindOneAsync.cs - :start-after: start-find-builders - :end-before: end-find-builders - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method - to asynchronously find one document, see the `Asynchronous Find One Example <{+example+}/find-one/FindOneAsync.cs>`__. - -Find a Document by Using LINQ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following example uses LINQ to find a document in the ``restaurants`` -collection that has a ``name`` field with a value of "Bagels N Buns". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: linq-sync - - .. literalinclude:: ../includes/code-examples/find-one/FindOne.cs - :start-after: start-find-linq - :end-before: end-find-linq - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method - to synchronously find one document, see the `Synchronous Find One Example - <{+example+}/find-one/FindOne.cs>`__. - - .. tab:: Asynchronous - :tabid: linq-async - - .. literalinclude:: ../includes/code-examples/find-one/FindOneAsync.cs - :start-after: start-find-linq - :end-before: end-find-linq - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of using the ``Find()`` method - to asynchronously find one document, see the `Asynchronous Find One Example <{+example+}/find-one/FindOneAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running any of the preceding full examples prints results similar to the following: - -.. code-block:: none - - { - "_id" : ObjectId("5eb3d668b31de5d588f42950"), - "name" : "Bagels N Buns", - "restaurant_id" : "40363427", - "cuisine" : "Delicatessen", - "address" : {...}, - "borough" : "Staten Island", - "grades" : [...] - } - -Additional Information ----------------------- - -To learn more about retrieving documents, see the :ref:`csharp-retrieve` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -To learn how to find a document using LINQ, see :ref:`csharp-linq`. - -API Documentation ------------------ - -- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ -- `FirstOrDefault() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluentExtensions.FirstOrDefault.html>`__ -- `FirstOrDefaultAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.FirstOrDefaultAsync.html>`__ diff --git a/source/usage-examples/insertMany.txt b/source/usage-examples/insertMany.txt deleted file mode 100644 index 51252382..00000000 --- a/source/usage-examples/insertMany.txt +++ /dev/null @@ -1,83 +0,0 @@ -.. _csharp-insert-many: - -========================= -Insert Multiple Documents -========================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Learn to insert multiple documents into a collection using C# with synchronous and asynchronous methods. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can insert multiple documents into a collection by using the synchronous -``InsertMany()`` method or the asynchronous ``InsertManyAsync()`` method. - -Example -------- - -The following example inserts multiple documents into -the ``restaurants`` collection. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: insert-many-sync - - .. literalinclude:: ../includes/code-examples/insert-many/InsertMany.cs - :start-after: start-insert-many - :end-before: end-insert-many - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``InsertMany()`` operation, see the - `InsertMany code sample <{+example+}/insert-many/InsertMany.cs>`__. - - .. tab:: Asynchronous - :tabid: insert-many-async - - .. literalinclude:: ../includes/code-examples/insert-many/InsertManyAsync.cs - :start-after: start-insert-many - :end-before: end-insert-many - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``InsertManyAsync()`` operation, see the - `InsertManyAsync code sample <{+example+}/insert-many/InsertManyAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -After running either of the preceding full examples, the output is as follows: - -.. code-block:: none - - Number of restaurants found before insert: 0 - - Inserting documents... - Number of restaurants inserted: 5 - - -Additional Information ----------------------- - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -- `InsertMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertMany.html>`__ -- `InsertManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertManyAsync.html>`__ diff --git a/source/usage-examples/insertOne.txt b/source/usage-examples/insertOne.txt deleted file mode 100644 index 3bf2fddc..00000000 --- a/source/usage-examples/insertOne.txt +++ /dev/null @@ -1,83 +0,0 @@ -.. _csharp-insert-one: - -================= -Insert a Document -================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Insert a single document into a collection using C# with either the synchronous `InsertOne()` or asynchronous `InsertOneAsync()` method. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can insert a single document into a collection by using the synchronous -``InsertOne()`` method, or the asynchronous ``InsertOneAsync()`` method. - -Example -------- - -The following example inserts a document into the ``restaurants`` collection. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: insert-one-sync - - .. literalinclude:: ../includes/code-examples/insert-one/InsertOne.cs - :start-after: start-insert-one - :end-before: end-insert-one - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``InsertOne()`` operation, see the - `Synchronous Insert One Example <{+example+}/insert-one/InsertOne.cs>`__. - - .. tab:: Asynchronous - :tabid: insert-one-async - - .. literalinclude:: ../includes/code-examples/insert-one/InsertOneAsync.cs - :start-after: start-insert-one-async - :end-before: end-insert-one-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``InsertOneAsync()`` operation, see the - `Asynchronous Insert One Example <{+example+}/insert-one/InsertOneAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -After running either of the preceding full examples, the ``InsertOne()`` -method inserts the document, and the :ref:`Find() ` method returns -the newly inserted document. The output is similar to the following: - -.. code-block:: none - - Inserting a document... - Document Inserted: { "_id" : ObjectId("..."), "name" : "Mongo's Pizza", "restaurant_id" : "12345", "cuisine" : "Pizza", "address" : { "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { "street" : "Pizza St", "zipcode" : "10003" } }, "borough" : "Manhattan", "grades" : [{ "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { } }] } - -Additional Information ----------------------- - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -- `InsertOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertMany.html>`__ -- `InsertOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertOneAsync.html>`__ -- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ -- `FirstOrDefault() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluentExtensions.FirstOrDefault.html>`__ diff --git a/source/usage-examples/replaceOne.txt b/source/usage-examples/replaceOne.txt deleted file mode 100644 index c3832012..00000000 --- a/source/usage-examples/replaceOne.txt +++ /dev/null @@ -1,89 +0,0 @@ -.. _csharp-replace-one: - -================== -Replace a Document -================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Replace a document in a collection using the `ReplaceOne()` or `ReplaceOneAsync()` methods, with examples for both synchronous and asynchronous operations. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can replace one document with another by using the ``ReplaceOne()`` synchronous method -or the ``ReplaceOneAsync()`` asynchronous method on a collection object. - -Example -------- - -The following code replaces the first document in the ``restaurants`` collection that has a -value of "Pizza" in the ``cuisine`` field. After the replacement, this document will -have a ``name`` field with a value of "Mongo's Pizza" and new values for the -``address`` and ``borough`` fields. - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: replace-one-sync - - .. literalinclude:: ../includes/code-examples/replace-one/ReplaceOne.cs - :start-after: start-replace-one - :end-before: end-replace-one - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``ReplaceOne()`` operation, see the - `ReplaceOne code sample <{+example+}/replace-one/ReplaceOne.cs>`__. - - .. tab:: Asynchronous - :tabid: replace-one-async - - .. literalinclude:: ../includes/code-examples/replace-one/ReplaceOneAsync.cs - :start-after: start-replace-one-async - :end-before: end-replace-one-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``ReplaceOneAsync()`` operation, see the - `ReplaceOneAsync code sample <{+example+}/replace-one/ReplaceOneAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running either of the preceding full examples prints the following results: - -.. code-block:: none - - First pizza restaurant before replacement: J&V Famous Pizza - Restaurants modified by replacement: 1 - First pizza restaurant after replacement: Mongo's Pizza - Resetting sample data...done. - -Additional Information ----------------------- - -To learn more about replacing documents, see the :ref:`csharp-replace-operation` -guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ -* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ -* `ReplaceOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ -* `ReplaceOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOneResult.html>`__ \ No newline at end of file diff --git a/source/usage-examples/updateMany.txt b/source/usage-examples/updateMany.txt deleted file mode 100644 index f8e5f99f..00000000 --- a/source/usage-examples/updateMany.txt +++ /dev/null @@ -1,87 +0,0 @@ -.. _csharp-examples-update-many: - -===================== -Update Many Documents -===================== - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Update multiple documents in a collection using the `UpdateMany()` method to change specific field values. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can update more than one document using the ``UpdateMany()`` method on -a collection object. - -Example -------- - -The following code updates all documents in the ``restaurants`` collection that have a -``cuisine`` field with the value of "Pizza". After the update, these documents will -have a ``cuisine`` field with a value of "Pasta and breadsticks". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding -code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: update-many-sync - - .. literalinclude:: ../includes/code-examples/update-many/UpdateMany.cs - :start-after: start-update-many - :end-before: end-update-many - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``UpdateMany()`` operation, see the - `UpdateMany code sample <{+example+}/update-many/UpdateMany.cs>`__. - - .. tab:: Asynchronous - :tabid: update-many-async - - .. literalinclude:: ../includes/code-examples/update-many/UpdateManyAsync.cs - :start-after: start-update-many-async - :end-before: end-update-many-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``UpdateManyAsync()`` operation, see the - `UpdateManyAsync code sample <{+example+}/update-many/UpdateManyAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -Running either of the preceding full examples prints the following results: - -.. code-block:: none - - Restaurants with cuisine "Pizza" found: 1163 - Restaurants modified by update: 1163 - Restaurants with cuisine "Pasta and breadsticks" found after update: 1163 - Resetting sample data...done. - -More Information ----------------- - -To learn more about updating documents, see the :ref:`csharp-update-many` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -* `UpdateMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateMany.html>`__ -* `UpdateManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateManyAsync.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ \ No newline at end of file diff --git a/source/usage-examples/updateOne.txt b/source/usage-examples/updateOne.txt deleted file mode 100644 index b0d02b43..00000000 --- a/source/usage-examples/updateOne.txt +++ /dev/null @@ -1,98 +0,0 @@ -.. _csharp-examples-update-one: - -================= -Update a Document -================= - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: code example, .NET, operation - :description: Learn how to update a single document in a MongoDB collection using the `UpdateOne()` method with C# drivers. - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -You can update a single document using the `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ method on -a ``MongoCollection`` object. This method requires a **query filter**, which specifies which document to update, and an **update** statement, which specifies the changes the driver should make to the first document matching the query filter. - -.. note:: - - The ``UpdateOne()`` method updates only the first document that matches the - filter. To update more than one document, use the :ref:`UpdateMany() method `. - -.. tip:: - - You can pass an instance of `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ to the ``UpdateOne()`` method in - order to customize its behavior. - -Example -------- - -The following example uses ``Builders`` to update the ``name`` of the -first document named "Bagels N Buns" in the ``restaurants`` collection to -"2 Bagels 2 Buns". - -Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the -corresponding code. - -.. tabs:: - - .. tab:: Synchronous - :tabid: update-many-sync - - .. literalinclude:: ../includes/code-examples/update-one/UpdateOne.cs - :start-after: start-update-one - :end-before: end-update-one - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``UpdateOneAsync()`` operation, see the - `UpdateOne Example <{+example+}/update-one/UpdateOne.cs>`__. - - .. tab:: Asynchronous - :tabid: update-async - - .. literalinclude:: ../includes/code-examples/update-one/UpdateOneAsync.cs - :start-after: start-update-one-async - :end-before: end-update-one-async - :language: csharp - :copyable: - :dedent: - - For a fully runnable example of the ``UpdateOneAsync()`` operation, see the - `UpdateOneAsync Example <{+example+}/update-one/UpdateOneAsync.cs>`__. - -Expected Result -~~~~~~~~~~~~~~~ - -After running either of the preceding full examples, each call to ``UpdateOne()`` -writes the following to the console: - -.. code-block:: none - - Updated documents: 1 - -.. tip:: - - ``UpdateOne()`` returns an `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ object. - -More Information ----------------- - -To learn more about updating documents, see the :ref:`csharp-update-one` guide. - -To learn more about using builders, see :ref:`csharp-builders`. - -API Documentation ------------------ - -* `UpdateOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.UpdateOne.html>`__ -* `UpdateOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOptions.html>`__ -* `UpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateResult.html>`__ \ No newline at end of file