mongo-csharp-driver / MongoDB.Driver
AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub
This file is the entry point for any work under src/MongoDB.Driver/. Over 200 .cs files at this directory root are predominantly the public API surface — client facades, builders DSL, fluent APIs, and option/result types — though a meaningful minority (~20%) are internal helpers that happen to live alongside it. Public API is not confined to this directory: Core/, Core/Events/, Core/Logging/, GridFS/, Search/, Linq/, GeoJsonObjectModel/, and the MongoDB.Bson project also expose public types. Subdirectories own their own deep concerns and…
Trending
Quiet since September.about the whole repository
Who's talking about mongodb/mongo-csharp-driver
- jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources“Support for latest MongoDB library with signing”GitHub · Jul 28, 2024 · 13 reactions
- opensearch-project/opensearch-net“[FEATURE] Add LINQ Support to the OpenSearch C# Client”GitHub · Sep 18, 2023 · 5 reactions
- nopSolutions/nopCommerce“MongoDB database support”GitHub · Apr 30, 2019 · 4 reactions
- microsoft/aspire“MongoDB.Driver v3 breaks Aspire.MongoDB.Driver integration”GitHub · Oct 18, 2024 · 3 reactions
- jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources“Deprecate this package”GitHub · Apr 21, 2026 · 2 reactions
The biggest 5 of 40 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 40
Talked about on GitHub (40 times).
On GitHub · 40
- Jul 28, 2024Support for latest MongoDB library with signing — jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources13 reactions · 5 comments
- Sep 18, 2023[FEATURE] Add LINQ Support to the OpenSearch C# Client — opensearch-project/opensearch-net5 reactions · 1 comment
- Apr 30, 2019MongoDB database support — nopSolutions/nopCommerce4 reactions · 24 comments
- Oct 18, 2024MongoDB.Driver v3 breaks Aspire.MongoDB.Driver integration — microsoft/aspire3 reactions · 9 comments
- Apr 21, 2026Deprecate this package — jbogard/MongoDB.Driver.Core.Extensions.DiagnosticSources2 reactions · 1 comment
35 more on GitHub
- Nov 5, 2025Corrected Membership Session Handling — OrleansContrib/Orleans.Providers.MongoDB2 reactions · 2 comments
- Jun 4, 2016Support .NET Core — tugberkugurlu/AspNetCore.Identity.MongoDB2 reactions · 1 comment
- Jul 12, 2026Upgrade MongoDB.Driver to 3.9.0 to fix Snappier and SharpCompress vulnerabilities — madelson/DistributedLock1 reaction
- May 28, 2026Upgrade MongoDB.Driver to 3.9.0 — abpframework/abp1 reaction · 1 comment
- May 12, 2026Upgrade MongoDB.Driver to 3.8.1 — abpframework/abp1 reaction
- Mar 19, 2026bump MongoDB.Driver to 3.7.1 — abpframework/abp1 reaction
- Jan 18, 2026Update MongoDB.Driver package version to 3.6.0 — abpframework/abp1 reaction · 1 comment
- Nov 20, 2025Update MongoDB.Driver to version 3.5.1 — abpframework/abp1 reaction
- Jan 30, 2023Hangfire.Mongo is incompatible with the MongoDB.Driver LINQ3 provider — gottscj/Hangfire.Mongo1 reaction · 1 comment
- Jun 6, 2022Mongo Driver Compatibility — alirezanet/Gridify1 reaction · 3 comments
- Mar 31, 2015Support for 2.0 async driver — RobThree/MongoRepository1 reaction · 35 comments
- Sep 29, 2026Bump MongoDB.Driver from 2.11.5 to 2.19.0 — ramonaoldf/run-devops0 reactions
- Sep 15, 2026Bump the nuget group with 1 update — ApurvSinghal/ApurvXam0 reactions
- Aug 2, 2026Bump MongoDB.Driver from 2.8.1 to 2.19.0 — mohaom/TailwindTraders-Website0 reactions
- Jan 12, 2025Bump MongoDB.Driver from 2.14.1 to 2.19.0 in /src/Infrastructure — vigovlugt/LeagueOfItemsBackend0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.19.0 [SECURITY] — MrDariusAD/DynamicFilter0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.12.2 [SECURITY] — ShamKarthikS-Hexaware/recicd0 reactions
- Aug 6, 2024Update dependency MongoDB.Driver to 2.12.2 [SECURITY] — MrDariusAD/GirlfriendAdventskalender0 reactions
- Jan 15, 2024Bump MongoDB.Driver.Core and MongoDB.Bson — kravvya/GardenLog.V20230 reactions
- Nov 17, 2023build(deps): bump MongoDb_Version from 2.19.0 to 2.22.0 — AntonioFalcaoJr/EventualShop0 reactions
- Mar 28, 2023Bump MongoDB.Driver from 2.19.0 to 2.19.1 — eincioch/dotnet-microservices-boilerplate0 reactions
- Mar 27, 2023Bump MongoDB.Driver from 2.19.0 to 2.19.1 — niaz-ali-khan/microservise0 reactions
- Mar 3, 2023Bump MongoDB.Driver from 2.13.1 to 2.19.0 in /DotNet/POC/DatabaseBenchmark — AdamNagy/Nadam.Tryouts0 reactions
- Mar 3, 2023Bump MongoDB.Driver from 2.12.3 to 2.19.0 in /Esiur.Stores.MongoDB — esiur/esiur-dotnet0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.17.1 to 2.18.0 in /src/backend — ScottishTapWater/OrderBook0 reactions
- Oct 17, 2022fix(deps): bump MongoDB.Driver from 2.16.1 to 2.18.0 — Manu0912/doppler-push-contact0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.13.0 to 2.18.0 — uruk-project/uruk-server0 reactions
- Oct 17, 2022Bump MongoDB.Driver from 2.15.1 to 2.18.0 — joelbyford/ApiPatternsClient0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.13.1 to 2.18.0 in /examples/AspNetCoreMvc — brucehu123/opentelemetry-dotnet-instrumentation0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/common/Platform.Common — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/lobby/Platform.Lobby.Tests — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/eucre-game/Games.Eucre.Api — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/weather/Weather.Api — frogsbreath-games/eucre0 reactions
- Oct 14, 2022Bump MongoDB.Driver from 2.12.4 to 2.18.0 in /services/library/Platform.Library.Api — frogsbreath-games/eucre0 reactions
- May 24, 2022Bump MongoDB.Driver from 2.13.1 to 2.15.1 in /examples/AspNetCoreMvc — brucehu123/opentelemetry-dotnet-instrumentation0 reactions
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- src/MongoDB.Bson/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Authentication/AGENTS.mdAGENTS.md
- src/MongoDB.Driver.Authentication.AWS/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Bindings/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Events/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Logging/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Core/Operations/AGENTS.mdAGENTS.md
- src/MongoDB.Driver.Encryption/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Encryption/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/GeoJsonObjectModel/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/GridFS/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Linq/AGENTS.mdAGENTS.md
- src/MongoDB.Driver/Search/AGENTS.mdAGENTS.md
- tests/MongoDB.Driver.TestHelpers/AGENTS.mdAGENTS.md
- tests/MongoDB.Driver.Tests/Specifications/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- src/MongoDB.Bson/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver.Authentication.AWS/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Authentication/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Bindings/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Events/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Logging/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Core/Operations/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver.Encryption/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Encryption/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/GeoJsonObjectModel/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/GridFS/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Linq/CLAUDE.mdCLAUDE.md
- src/MongoDB.Driver/Search/CLAUDE.mdCLAUDE.md
- tests/MongoDB.Driver.TestHelpers/CLAUDE.mdCLAUDE.md
- tests/MongoDB.Driver.Tests/Specifications/CLAUDE.mdCLAUDE.md
The file
We split this AGENTS.md into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 135
When in doubt, add an [Obsolete] overload first and route through the new path.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MongoDB.Driver — AGENTS.md (router)
This file is the entry point for any work under src/MongoDB.Driver/. Over 200 .cs files at this directory root are predominantly the public API surface — client facades, builders DSL, fluent APIs, and option/result types — though a meaningful minority (~20%) are internal helpers that happen to live alongside it. Public API is not confined to this directory: Core/, Core/Events/, Core/Logging/, GridFS/, Search/, Linq/, GeoJsonObjectModel/, and the MongoDB.Bson project also expose public types. Subdirectories own their own deep concerns and have their own AGENTS.md. This file holds substantive guidance only for code that actually lives at the root.
Area router
| If you're editing… | See |
Core/Clusters/, Core/Servers/, Core/Connections/, Core/ConnectionPools/, Core/WireProtocol/, Core/Compression/, Core/Configuration/, Core/Misc/ | Core/AGENTS.md (Connection & Transport / SDAM) |
Core/Operations/, Core/Bindings/, plus ClientSession*.cs, CoreSession* | Core/Operations/AGENTS.md (Operations, Sessions & Transactions) |
Authentication/ | Authentication/AGENTS.md |
Linq/, Linq/Linq3Implementation/ | Linq/AGENTS.md (LINQ provider) |
GridFS/ | GridFS/AGENTS.md |
Search/ | Search/AGENTS.md (Atlas Search & Vector Search) |
Encryption/ (driver-side glue) | Encryption/AGENTS.md and the sibling src/MongoDB.Driver.Encryption/AGENTS.md (libmongocrypt) |
Core/Events/, Core/Logging/ | Core/Events/AGENTS.md and Core/Logging/AGENTS.md |
GeoJsonObjectModel/ | GeoJsonObjectModel/AGENTS.md |
The substantive sections below cover only files that live in src/MongoDB.Driver/ directly.
Scope (root files)
User-facing facades, fluent APIs, builders, and option/result records. The OperationExecutor at this layer dispatches to Core/Operations/; everything below the wire is in Core/.
Client facades & settings
MongoClient.cs/IMongoClient.cs— top-level entry. Constructors: parameterless (defaults tomongodb://localhost), or one acceptingMongoClientSettings,MongoUrl, or a connection string. Holds the cluster reference;Dispose()shuts down connections.IMongoDatabase.cs/MongoDatabase.cs,IMongoCollection.cs/MongoCollectionImpl.cs(definingMongoCollectionImpl<TDocument>) — derived from the client; carry their own settings (read/write concern, read preference, serializer registry). The public abstractions are the interfacesIMongoDatabaseandIMongoCollection<TDocument>;MongoDatabase,MongoCollectionBase<TDocument>, andMongoCollectionImpl<TDocument>are allinternal.- Settings types —
MongoClientSettings,MongoDatabaseSettings,MongoCollectionSettings,SslSettings,MongoUrl,MongoUrlBuilder,MongoServerAddress,MongoCredential(and identity subtypes),AutoEncryptionOptions,ClusterKey. (ServerApiis part of the same surface — surfaced viaMongoClientSettings.ServerApi— but the type lives atCore/ServerApi.cs, not at the driver root.)MongoUrlvsMongoUrlBuilder:MongoUrlis immutable (parsed from a connection string, exposes only getters and aToString()round-trip);MongoUrlBuilderis the mutable builder counterpart used to assemble or mutate a connection string before callingToMongoUrl()for the immutable form.
Settings freeze invariant. All *Settings types are mutable until Freeze() is called. The driver freezes settings when they're passed into a client/database/collection. After that, mutation throws. Treat settings as immutable once handed to the framework — clone before mutating.
OperationExecutor / IOperationExecutor — internal seam between facades and Core/Operations (defined in IOperationExecutor.cs and OperationExecutor.cs; not part of the public API). All public methods bottom out by constructing a Core/Operations operation and handing it to the executor. Don't bypass it; retry, session attachment, and command-monitoring hooks live there.
Builders DSL
Hub: Builders<TDocument> (Builders.cs) exposes the six core builder properties — listed alphabetically to match the source: Filter, IndexKeys, Projection, SetFields, Sort, Update — plus the Atlas Search builder hubs (Search, SearchPath, SearchScore, SearchScoreFunction, SearchFacet, SearchSpan). Each property returns a builder that produces an immutable *Definition<TDocument>.
The same *Definition / *DefinitionBuilder pattern is used by FilterDefinition*, UpdateDefinition*, ProjectionDefinition*, SortDefinition*, IndexKeysDefinition*, SetFieldDefinitions*. SetFields is the odd one out in that family: the builder is singular (SetFieldDefinitionsBuilder<T>) but the definition it produces is plural (SetFieldDefinitions<T>, a collection). Don't grep for a non-existent SetFieldDefinitionBuilder. PipelineDefinition* and PipelineStageDefinition* follow the same shape, but their helpers are the standalone static classes PipelineDefinitionBuilder / PipelineStageDefinitionBuilder rather than properties on Builders<T>. FieldDefinition and ArrayFilterDefinition are definition-only — polymorphic subtypes are constructed directly, with no builder hub. For fields specifically, there are two parallel generic shapes: FieldDefinition<T> (untyped field) with StringFieldDefinition<T> / ExpressionFieldDefinition<T> subclasses, and FieldDefinition<T, TField> (typed field, used when the projected field's CLR type matters) with StringFieldDefinition<T, TField> / ExpressionFieldDefinition<T, TField> subclasses. Renders bottom out in RenderedFieldDefinition / RenderedFieldDefinition<TField>.
- A
*Definition<T>is an abstract immutable that knows how toRender(RenderArgs<T>)to BSON. Most types render to aBsonDocument, with three notable exceptions.UpdateDefinition<T>.Renderreturns the broaderBsonValuebecause pipeline-form updates render as aBsonArray; cast accordingly when asserting against rendered output. The two-genericProjectionDefinition<TSource, TProjection>.RenderreturnsRenderedProjectionDefinition<TProjection>(a wrapper ofBsonDocumentplus the projection-result serializer); only the single-genericProjectionDefinition<TSource>.Renderreturns a bareBsonDocument.PipelineDefinition<TInput, TOutput>.RenderreturnsRenderedPipelineDefinition<TOutput>(a wrapper ofIReadOnlyList<BsonDocument>plus the output serializer), not aBsonDocument. Signature outlier:ArrayFilterDefinition<TItem>.Renderdoes not takeRenderArgs<T>— it exposes two overloads, the non-genericRender(IBsonSerializer itemSerializer, IBsonSerializerRegistry serializerRegistry)declared on the baseArrayFilterDefinitionand the typedRender(IBsonSerializer<TItem> itemSerializer, IBsonSerializerRegistry serializerRegistry)onArrayFilterDefinition<TItem>(seeArrayFilterDefinition.cs:46and:103). Don't waste time grepping for aRenderArgsoverload on it. - A
*DefinitionBuilder<T>constructs concrete definitions via fluent methods. Implicit conversions vary by definition type. Most accept
BsonDocumentandstring(parsed as JSON — a frequent overload-ambiguity hazard); theFieldDefinitionfamily accepts onlystring;SetFieldDefinitions<T>accepts nothing. The full matrix:Definition type BsonDocumentstring(JSON)Other implicit conversions FilterDefinition<T>✅ ✅ Expression<Func<T, bool>>UpdateDefinition<T>✅ ✅ PipelineDefinition<T, T>(pipeline-update form)ProjectionDefinition<TSource>✅ ✅ — ProjectionDefinition<TSource, TProjection>✅ ✅ ProjectionDefinition<TSource>(up-cast adding projection-result type)SortDefinition<T>✅ ✅ — IndexKeysDefinition<T>✅ ✅ — ArrayFilterDefinition<TItem>✅ ✅ (JSON) — FieldDefinition<T>❌ ✅ (treated as a literal field name via StringFieldDefinition<T>— not JSON-parsed; this is the asymmetry vs. the other definitions' string conversions, and it applies family-wide —FieldDefinition<TDocument, TField>below behaves the same way)— FieldDefinition<TDocument, TField>❌ ✅ (also a literal field name) up-cast to FieldDefinition<TDocument>(drops field-CLR-type parameter)PipelineDefinition<TInput, TOutput>❌ — IPipelineStageDefinition[],List<IPipelineStageDefinition>,BsonDocument[],List<BsonDocument>(arrays/lists ofBsonDocument, not a singularBsonDocument— wrap a single doc innew[] { doc }to use the array conversion)SetFieldDefinitions<T>(plural, the collection type exposed viaBuilders<T>.SetFields; distinct from the singularSetFieldDefinition<T>, nos)❌ ❌ — The four
PipelineDefinition<TInput, TOutput>array/list conversions are a known overload-resolution hazard: a method overloaded on bothPipelineDefinition<…>and one of those collection shapes may resolve to either depending on the call site.Expression<Func<T, bool>>is implicit-convertible only onFilterDefinition<T>; other definitions accept LINQ expressions exclusively via builder methods.
Render is where bugs hide. Render receives RenderArgs<TDocument> carrying the active serializer registry, document serializer, and translation options. A definition rendered with the wrong document serializer produces silently-wrong BSON — never compile errors. When changing builder behavior, add a test that compares the rendered BSON, not just round-trip behavior.
Pitfall: lambda overload ambiguity. Builders have many Expression<Func<…>> overloads. The C# compiler sometimes picks the wrong one — be explicit with type parameters when refactoring.
Aggregation fluent API
IAggregateFluent<TResult>/AggregateFluentBase<TResult>(public abstract) /AggregateFluent<TInput,TResult>(internal abstract) — fluent stage chaining over aPipelineDefinition.- Stage options and result records:
AggregateOptions(consultAggregateOptions.csfor the full list of properties; load-bearing ones includeAllowDiskUse,BatchSize,Comment,Hint,MaxTime,MaxAwaitTime,Collation,Let,BypassDocumentValidation, andTranslationOptions;UseCursoris[Obsolete]and new code should not propagate it to any new API surface),AggregateBucket*,AggregateFacet*,AggregateGraphLookupOptions,AggregateLookupOptions,AggregateUnwindOptions.AggregateHelperisinternal static(a render helper), not part of the public surface.MaxAwaitTime(here onAggregateOptions, mirrored onChangeStreamOptions) is honored only by tailable / change-stream cursors (it bounds the server-side wait ongetMore); it is inert for ordinary aggregation cursors — seeAggregateOptions.csfor the property definition and surrounding context. Don't set it expecting it to bound a regular aggregation. AggregateExpressionDefinition<TSource, TResult>is separate — an aggregation-expression abstraction with concrete subclassesBsonValueAggregateExpressionDefinition<TSource, TResult>,ExpressionAggregateExpressionDefinition<TSource, TResult>, andDocumentsAggregateExpressionDefinition<TDocument>. The last is the input shape for$documentsand is consumed via thePipelineStageDefinitionBuilder.Documents(...)helper, which produces the first stage on a client- or database-levelAggregate(...); there is no collection-level fluent equivalent (collection-level aggregates run against the collection itself). Used by stage builders that take expression arguments, not itself a stage option.- Bottoms out in
Core/Operations/AggregateOperation<T>andAggregateToCollectionOperation(for$out/$merge).
Boundary with operations-reviewer: this layer owns stage shape and pipeline semantics. The Operations layer owns cursor lifecycle, retry, and binding selection.
Change streams
ChangeStreamOptions,ChangeStreamPreAndPostImagesOptions,ChangeStreamStageOptions.ChangeStreamHelperisinternal static(an internal render helper), not part of the public surface.- Entry points
IMongoClient.Watch(cluster-wide),IMongoDatabase.Watch(db-wide),IMongoCollection.Watch(collection-scoped). Bottoms out inCore/Operations/ChangeStreamOperationandChangeStreamCursor.
The change-stream pipeline input type is ChangeStreamDocument<BsonDocument> for client- and database-level watches and ChangeStreamDocument<TDocument> for collection-level watches; only the output type is user-defined. Stages that materialize results ($out, $merge) are rejected by the server in a change-stream pipeline — the driver does not validate this client-side. If client-side validation is ever added, treat the change in which stages are legal as a SemVer-relevant behavior change, not a pure bug-fix.
Resume tokens are opaque. The resume token round-trips as an opaque BsonDocument — ResumeAfter / StartAfter accept whatever shape the server emitted in _id on a prior change event. Do not normalize, reshape, prune fields from, or stringify-and-reparse the token: the server treats it as a black box, and any client-side rewrite risks producing a token the server will reject or — worse — that points to a different resume position.
Sessions surface
- Public:
IClientSessionHandle(declared inIClientSession.csalongsideIClientSession); the implementationClientSessionHandle(inClientSessionHandle.cs) isinternal sealed.ClientSessionOptionsis public;AbortTransactionOptionsandCommitTransactionOptionsare currentlyinternal sealed— the user-facing public abstraction is justClientSessionOptions. Theinternalvisibility on these two options types is gated on CSOT GA; expect them to be promoted topublic(a SemVer-additive change) when CSOT ships, so don't bake assumptions about their internal-ness into long-lived code. ClientSessionHandlewrapsICoreSessionHandle(declared inCore/Bindings/ICoreSession.cs; the implementation isCoreSessionHandleinCore/Bindings/CoreSessionHandle.cs, which wraps the underlyingCoreSessionfromCore/Bindings/CoreSession.cs).
Ownership boundary. The client-api-reviewer owns only the surface-level interface (constructors, properties, IMongoClient.StartSession*). Session state, transaction state machine, cluster time, server pinning, and retryable-transaction semantics belong to the operations-reviewer (see Core/Operations/AGENTS.md).
Find fluent API
IFindFluent<TDocument,TProjection>/FindFluentBase<TDocument,TProjection>(public abstract) /FindFluent<TDocument,TProjection>(internal) — chain Skip/Limit/Sort/Project/etc.FindOptions<TDocument,TProjection>,FindOneAndUpdateOptions,FindOneAndDeleteOptions,FindOneAndReplaceOptions.Countis[Obsolete]onIFindFluent— useCountDocumentson the fluent surface. (EstimatedDocumentCountlives onIMongoCollection<T>, not on the find-fluent surface.) Per the SemVer rules in Public-API change discipline below, removing the obsoleteCountrequires a major-version bump even though it has carried[Obsolete]for several release cycles.
Bulk write — two layers
Two parallel surfaces, do not mix them.
- Collection-level (
IMongoCollection<T>.BulkWriteAsync): single collection. Models derive fromWriteModel<T>(InsertOneModel<T>,UpdateOneModel<T>,UpdateManyModel<T>,DeleteOneModel<T>,DeleteManyModel<T>,ReplaceOneModel<T>). Result:BulkWriteResult<TDocument>. Failure:MongoBulkWriteException<TDocument>(the non-genericMongoBulkWriteExceptionis the abstract base —catchblocks should target the sealed generic). - Client-level (
IMongoClient.BulkWriteAsync, MongoDB 8.0+): cross-collection. Models derive fromBulkWriteModel. Result:ClientBulkWriteResult. Failure:ClientBulkWriteException(which carries partial results).
Index management
IMongoIndexManager<T>/MongoIndexManagerBase<T>for normal indexes.CreateIndexModel<T>,CreateIndexOptions—Unique,Sparse,Background, TTL (ExpireAfter), partial filter, collation.- Atlas Search index helpers:
CreateSearchIndexModel,SearchIndexType. Vector-search index models share a common base —CreateVectorSearchIndexModelBase<TDocument>— with concrete subclassesCreateVectorSearchIndexModel<TDocument>andCreateAutoEmbeddingVectorSearchIndexModel<TDocument>. Tests for these are gated byATLAS_SEARCH_INDEX_HELPERS_TESTS_ENABLED(see rootAGENTS.md).
Vector search surface
QueryVector,BinaryVectorExtensions,VectorSearchOptions,VectorEmbeddingModality,VectorIndexingMethod,VectorQuantization,VectorSimilarity.- The fluent search builders themselves live under
Search/— seeSearch/AGENTS.md.
Exceptions
MongoWriteException, MongoBulkWriteException, ClientBulkWriteException derive from the Core exception hierarchy. WriteError, WriteConcernError, BulkWriteError carry per-operation failure details. Network/transient errors are surfaced via the Core layer (MongoConnectionException, MongoServerException, etc.) — see Core/AGENTS.md.
Public-API change discipline
The driver root is a major SemVer surface — but not the only one. Public types also live under Core/, Core/Events/, Core/Logging/, GridFS/, Search/, Linq/, GeoJsonObjectModel/, and the MongoDB.Bson project. Treat additions as load-bearing; treat changes (signature, behavior, default options) as breaking, wherever they occur. Specifically:
- Adding overloads is fine; changing an existing default value is not.
- Renaming a property on a
*Optionsrecord is breaking. - Builders'
Renderoutput is a behavior contract — pipeline shape changes break user expectations even if the C# signature is unchanged. (LINQ3 translator changes are a separate exception class: pipeline-shape evolution there is governed by the LINQ provider's own translation-stability rules, not the builders contract — seeLinq/AGENTS.md.) - New methods on
IMongoClient/IMongoDatabase/IMongoCollectionbreak implementers (mocks, test doubles). Freeze()timing is a behavioral contract. Settings types (MongoClientSettings,MongoDatabaseSettings,MongoCollectionSettings,SslSettings, etc.) freeze when handed to the framework. Moving the freeze point earlier — or later — can break callers that currently mutate post-construction, even when no signature changes.
When in doubt, add an [Obsolete] overload first and route through the new path.
How to test (root-level changes)
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~MongoCollectionImplTests|FullyQualifiedName~FilterDefinitionBuilderTests|FullyQualifiedName~UpdateDefinitionBuilderTests|FullyQualifiedName~ProjectionDefinitionBuilderTests|FullyQualifiedName~SortDefinitionBuilderTests|FullyQualifiedName~IndexKeysDefinitionBuilderTests|FullyQualifiedName~PipelineDefinitionBuilderTests|FullyQualifiedName~AggregateFluentTests"For builder rendering specifically: most tests under tests/MongoDB.Driver.Tests/ at the root assert against rendered BSON via .Render(...) rather than executing against a server — fast and deterministic. Prefer adding to that pattern.
JSON-driven CRUD spec tests in tests/MongoDB.Driver.Tests/Specifications/crud/ exercise the public API end-to-end — see tests/MongoDB.Driver.Tests/Specifications/AGENTS.md.
Common pitfalls
- Mutating settings after they've been handed to a
MongoClient/MongoDatabase/MongoCollection. Frozen → throws. - Passing the wrong
TDocumentto a builder, then rendering produces silently-wrong BSON. Tests should assert rendered BSON. - Confusing
WriteModel<T>(collection bulk) withBulkWriteModel(client bulk). Different result types and different exception types. - Forgetting that change-stream pipelines cannot end with materializing stages — the server rejects
$out/$mergein this position; the driver does not validate it. - Adding a new method to
IMongoCollection<T>without considering test doubles in user code — prefer extension methods onIMongoCollectionExtensions(apublic static class, parallelingIMongoClientExtensions) when the new functionality can compose existing methods. Naming note: this codebase keeps theIprefix on the type itself, not just the file name — theI-prefixed name on a non-interface is the established convention here, so match it. - Marking sync methods
Obsoletewithout keeping the async version — sync APIs are still load-bearing for many consumers.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

