mongo-csharp-driver / Operations
AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub
The execution layer between the public driver surface and the wire. Every public CRUD/aggregate/admin call eventually constructs one of these operations and hands it to an executor. This file's scope is wider than its directory: the operations-reviewer also owns Core/Bindings/, the session/transaction state machines, and the surface-level ClientSession* types at the driver root. (src/MongoDB.Driver/AbortTransactionOptions.cs and CommitTransactionOptions.cs are also in scope but are currently internal sealed — the user-facing public abstraction is ClientSessionOptions.) Two operation interfaces defined in Core/Operations/IOperation.cs (both internal;…
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/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.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
2 rules. About 0 are common, 0 are distinctive, and 2 are 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.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 96
Call operationContext.ThrowIfTimedOutOrCanceled() at the top of each iteration.
- Very specific: line 134
Recovery-token loss: If a sharded transaction's recovery token is lost (object thrown away mid-flow), commit/abort retries against a fresh …
≈ “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
Core/Operations — AGENTS.md (Operations, Sessions & Transactions)
The execution layer between the public driver surface and the wire. Every public CRUD/aggregate/admin call eventually constructs one of these operations and hands it to an executor. This file's scope is wider than its directory: the operations-reviewer also owns Core/Bindings/, the session/transaction state machines, and the surface-level ClientSession* types at the driver root. (src/MongoDB.Driver/AbortTransactionOptions.cs and CommitTransactionOptions.cs are also in scope but are currently internal sealed — the user-facing public abstraction is ClientSessionOptions.)
Operation hierarchy
Two operation interfaces defined in Core/Operations/IOperation.cs (both internal; the file is named IOperation.cs but contains only the two interfaces below — there is no shared IOperation base type):
IReadOperation<TResult>—Execute(OperationContext, IReadBinding)+ExecuteAsync(...). ReturnsTResult(oftenIAsyncCursor<T>).IWriteOperation<TResult>—Execute(OperationContext, IWriteBinding)+ExecuteAsync(...).
Both interfaces also expose a string OperationName { get; } property (see IOperation.cs); diagnostics layers use it to label the operation in events and logs.
Plus retry-aware variants in Core/Operations/IRetryableOperation.cs:
IExecutableInRetryableReadContext<TResult>— acceptsRetryableReadContextinstead of a raw binding.IExecutableInRetryableWriteContext<TResult>— write counterpart.
Most operations expose both sync and async; the retryable variants additionally expose Execute / ExecuteAsync overloads that take the relevant RetryableReadContext / RetryableWriteContext instead of a raw binding (there is no separate *WithContext method name — it's just an overload). When you fix a bug in one path, fix it in the matching other paths the operation actually defines.
Categories
- Find / Read:
FindOperation<T>,CountOperation,DistinctOperation<T>,EstimatedDocumentCountOperation,ListDatabasesOperation,ListCollectionsOperation,ListIndexesOperation,ReadCommandOperation<TCommandResult>. - Insert:
BulkInsertOperation(extendsBulkUnmixedWriteOperationBase<InsertRequest>),RetryableInsertCommandOperation. - Update / Delete / Replace:
BulkUpdateOperation,BulkDeleteOperation,RetryableUpdateCommandOperation,RetryableDeleteCommandOperation,FindOneAndUpdateOperation,FindOneAndDeleteOperation,FindOneAndReplaceOperation,BulkMixedWriteOperation(the engine forIMongoCollection.BulkWrite). - Aggregate:
AggregateOperation<T>,AggregateToCollectionOperation(for$out/$merge— implementsIRetryableWriteOperation<BsonDocument>for shape, but reportsIsOperationRetryable => falsebecause the trailing materializing stage forbids retry; sends a singleaggregaterunCommandwith the materializing stage in the pipeline rather than building a separate write payload).ChangeStreamOperationis also a read operation that returns a cursor. - Cursors:
AsyncCursor<T>(declaredinternal class— not sealed, so adjacent areas may derive; implementsIAsyncCursor<T>andICursorBatchInfo; the public constructor parameter is typed as the baseIChannelSource, but callers are expected to pass anIChannelSourceHandleso the channel source is reference-counted. ForgetMore, the cursor reuses its_channelSourcedirectly; the session fork (_channelSource.Session.Fork()) happens inside theChannelReadWriteBindingconstructed around it for the request — not as a separate step inGetNextBatch).ChangeStreamCursor<T>. - Cluster / Admin:
CreateIndexesOperation,DropIndexOperation,CreateCollectionOperation,DropCollectionOperation,RenameCollectionOperation,CreateViewOperation,CreateSearchIndexesOperation,DropSearchIndexOperation,UpdateSearchIndexOperation. - Transaction: abstract
EndTransactionOperationwithCommitTransactionOperationandAbortTransactionOperationderivatives. Both retryable.
Bindings (cross-ref to Core/Bindings/)
Bindings are how operations get to a server. The hierarchy in IBinding.cs (the IBinding interface family is internal, and the concrete binding implementations — ChannelReadBinding, ChannelReadWriteBinding, SingleServerReadBinding, SingleServerReadWriteBinding, ReadPreferenceBinding, WritableServerBinding, EndTransactionReadWriteBinding — are also internal sealed. The public types under Core/Bindings/ are the session/transaction Core* types — CoreSession, CoreSessionHandle, CoreSessionOptions, CoreTransaction, etc. See the boundary section below):
IBinding
├── IReadBinding GetReadChannelSource(OperationContext, …)
├── IWriteBinding GetWriteChannelSource(OperationContext, …)
└── IReadWriteBinding (combines both)A binding holds an ICoreSessionHandle. Concrete bindings include ChannelReadBinding, ChannelReadWriteBinding, SingleServerReadBinding, SingleServerReadWriteBinding, ReadPreferenceBinding, WritableServerBinding, EndTransactionReadWriteBinding. Some bindings (ReadPreferenceBinding, WritableServerBinding, SingleServerReadBinding) are decorators over a cluster-level binding that select a server; others (ChannelReadBinding, ChannelReadWriteBinding) are leaf bindings that hold an already-acquired pinned IChannelHandle (used post-pinning, e.g. inside transactions). The Get*ChannelSource methods also accept overloads for IReadOnlyCollection<ServerDescription> deprioritizedServers and (for writes) IMayUseSecondaryCriteria — both are part of the contract.
IChannelSource represents a route to a specific server. IChannelSourceHandle is reference-counted (Fork()); IChannelHandle (IChannel.cs) is the actual wire-protocol channel — its Command<TResult> and CommandAsync<TResult> methods bundle session, read preference, validators, and response handling.
Pinning. A session pins a channel and server at the start of a transaction. CoreTransaction itself is public, but the pinning members — PinnedChannel, PinnedServer, and UnpinAll() — are internal (see Core/Bindings/CoreTransaction.cs); they are not part of the SemVer surface. All subsequent ops in that transaction reuse the pinned route. Commit/abort use the pinned channel via EndTransactionReadWriteBinding. New transaction → transaction.UnpinAll().
Sessions, transactions, causal consistency
Three layers:
Session layers:
| Layer | Type | File |
| Public | ClientSessionHandle (impl), IClientSessionHandle (iface) | src/MongoDB.Driver/ClientSessionHandle.cs |
| Core | CoreSession | src/MongoDB.Driver/Core/Bindings/CoreSession.cs |
| Server-side state | ICoreServerSession (pooled in ICoreServerSessionPool) | Core/Bindings/CoreServerSession*.cs. The interface file itself is ICoreServerSesssion.cs with a triple-s typo — there is no non-typo'd file. Separately, the interface is declared in the MongoDB.Driver namespace, not MongoDB.Driver.Core.Bindings — relevant when grepping for the public type. |
Transaction state (orthogonal to the session layers): CoreTransaction (state machine) — Core/Bindings/CoreTransaction.cs.
ClientSessionHandle is a thin wrapper around ICoreSessionHandle — the surface holds nothing of substance. State lives in CoreSession.
Cluster time vs operation time
public BsonDocument ClusterTime => _clusterClock.ClusterTime; // shared
public BsonTimestamp OperationTime => _operationClock.OperationTime; // per-opCluster time advances after every server response (AdvanceClusterTime) and is gossiped between clients via the session. Causally-consistent reads include afterClusterTime: <latest>; the server waits for its applied cluster time to catch up before executing.
Transaction state machine
CoreTransactionState is Starting → InProgress → Committed | Aborted. StartTransaction:
- Increments
transactionNumber(AdvanceTransactionNumber()). - Creates a fresh
CoreTransaction(transactionNumber, options)with stateStarting. - Transitions to
InProgresson the first command.
Pinned channel/server attach on the first command. Recovery token (returned by mongos in sharded clusters) is stored on the transaction; commitTransaction re-uses it on retry to find the original mongos when a different one is contacted.
Unacknowledged writes are not allowed in transactions — CoreSession.StartTransaction throws InvalidOperationException ("Transactions do not support unacknowledged write concerns.") if the effective write concern is w: 0 at transaction-start time. The check fires once at start, not per-write.
Retryable reads & writes
RetryableReadOperationExecutor and RetryableWriteOperationExecutor are static loops that:
- Call
operationContext.ThrowIfTimedOutOrCanceled()at the top of each iteration. - Execute one attempt against the binding.
- On retryable exception, deprioritize the failed server. For ordinary retryable errors there is no back-off — the loop retries immediately against a different server. For
SystemOverloadedError-labelled exceptions an adaptive back-off (Thread.Sleepon the sync path,Task.Delayon the async path, computed byRetryabilityHelper.GetOperationRetryBackoffDelay(attempt, random)) is applied; both paths bail early if the back-off would exceed the remaining CSOT deadline (explicitif (remaining != Timeout.InfiniteTimeSpan && remaining < backoff) throw originalException;check before each sleep/delay inRetryableReadOperationExecutor.cs/RetryableWriteOperationExecutor.cs). The async path needs its own check becauseOperationContext.CancellationTokenis the raw caller token and does not fire when the CSOT deadline elapses —Task.Delay(backoff, operationContext.CancellationToken)would otherwise sleep the full back-off (up toMaxBackoff, or a server-suppliedbaseBackoffMS) regardless of the remaining timeout. The sync and async paths must stay separate here — do not collapse them by callingTask.Delay(...).GetAwaiter().GetResult()(sync-over-async on a hot retry path). - On non-retryable exception or attempt budget exhausted, throw.
Retry classification lives in RetryabilityHelper: network errors, the RetryableWriteError error label, and overload errors are retryable; auth/validation errors are not. Backpressure / SystemOverloadedError retries follow the separate adaptive-back-off path described above and are additionally gated by the enableOverloadRetargeting feature flag in both executors (RetryableReadOperationExecutor.cs / RetryableWriteOperationExecutor.cs) — with the flag off, overload errors do not get the adaptive back-off and behave like ordinary retryable errors. Both executors also take a maxAdaptiveRetries parameter (threaded through to RetryableReadContext / RetryableWriteContext) that bounds the adaptive-back-off retry count — it caps how many times the loop will sleep on the back-off path after observing a SystemOverloadedError, not the lifetime retry count from attempt 1. Once that adaptive cap is reached, the loop stops retrying even if the failure would otherwise be retryable. (See the ShouldRetry helper, defined in both RetryableReadOperationExecutor.cs and RetryableWriteOperationExecutor.cs.)
txnNumber bookkeeping. For retryable writes, the same txnNumber is reused across attempts — the server uses it to deduplicate. Don't increment it on retry. Retryable reads attach no txnNumber to their attempts. A session (lsid) is still required for retryable reads — txnNumber is the per-write deduplication tag; the lsid is what the server uses to identify the logical session, independent of write deduplication.
EndTransactionOperation is always retryable (commit/abort) at the executor layer — IsOperationRetryable returns true regardless of explicit retry-write configuration, so the executor will resubmit on a retryable error. This is a deliberate spec deviation from the general retryable-writes rule (which honours retryWrites=false): the transactions spec requires commitTransaction and abortTransaction to retry once even when retryable writes are otherwise disabled. The deeper server-side deduplication semantics for commitTransaction are governed by the same spec (recovery-token + txnNumber re-presented to a fresh mongos on retry), not by this flag. It reuses the pinned channel.
OperationContext
src/MongoDB.Driver/OperationContext.cs — bundles cancellation + deadline. The type itself is internal sealed, even though its members are public:
public CancellationToken CancellationToken { get; }
public TimeSpan? Timeout { get; } // null → infinite
public TimeSpan RemainingTimeout { get; } // Timeout - Elapsed, clamped at 0
public void ThrowIfTimedOutOrCanceled();It also carries optional OpenTelemetry metadata (operation name, db/collection names). It does not carry the binding or session — those are passed alongside.
CSOT propagation: every layer (executor → operation → binding → channel → wire protocol) must pass the context unchanged on the retry/operation path. Don't replace or wrap it on that path. There are a few narrow escape hatches in AsyncCursor for bounded cleanup work that must complete even when the parent deadline has expired — don't copy these patterns elsewhere:
KillCursors/KillCursorsAsync(inAsyncCursor.cs) bound the cursor-release request withoperationContext.WithTimeout(TimeSpan.FromSeconds(10))on their channel acquisition, so a server-side cursor still gets released. Called fromCloseIfNotAlreadyClosed(e.g. when a cursor finishes during iteration), not fromDisposedirectly.CloseIfNotAlreadyClosedFromDispose(inAsyncCursor.cs) uses a rawCancellationTokenSource(TimeSpan.FromSeconds(10))because noOperationContextis in scope on theDisposepath. Don't add new rawCancellationTokenSourcesubstitutions elsewhere to "match" this case.GetNextBatch/GetNextBatchAsync(inAsyncCursor.cs) andKillCursors/KillCursorsAsyncthemselves currently fabricate a freshOperationContext(null, cancellationToken)with a// TODO: CSOTcomment — a known gap, not a pattern to copy.
Skipping a ThrowIfTimedOutOrCanceled check at a re-entry point (next retry, next pool wait) is a stall risk.
Common pitfalls
- Sync/async path drift. Each operation has both, often duplicated; bug fixes need to touch both.
- Cursor disposal.
AsyncCursor<T>must be disposed (or fully iterated) to sendkillCursors. Otherwise the cursor lingers on the server. - Implicit vs explicit sessions. No
IClientSessionHandleparameter → driver creates an implicit session and disposes it. With an explicit session, the user must dispose — leaking is server-side memory growth. - Read concern on transactions. Transaction-level read/write concern overrides collection defaults. Don't pass operation-level overrides expecting them to win.
- Recovery-token loss. If a sharded transaction's recovery token is lost (object thrown away mid-flow), commit/abort retries against a fresh mongos can fail. Don't drop the
CoreTransactionreference. - Binding lifetime. Bindings are reference-counted (
Fork). Disposing the underlying channel-source while a forked handle is in use crashes the next operation. - Unacknowledged writes in transactions.
CoreSession.StartTransactionthrows when the effective write concern is unacknowledged; the rule isw >= 1always. - Server pinning persistence. Pinned channel doesn't unpin until a new transaction starts (
UnpinAll). Idle pinned connections are a real cost in long-running apps. OperationContextsubstitution. Wrapping or replacingOperationContextmid-call drops the deadline. Always pass through.- Retry on the wrong layer. This layer owns retry. The wire/transport layer (
Core/) reports errors and lets the retry executor decide. Don't add retry inside a binding or channel.
How to test
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Core.Operations|FullyQualifiedName~Core.Bindings"
# Sessions & transactions
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Sessions|FullyQualifiedName~Transactions"JSON-driven spec tests under:
tests/MongoDB.Driver.Tests/Specifications/sessions/tests/MongoDB.Driver.Tests/Specifications/transactions/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/tests/MongoDB.Driver.Tests/Specifications/crud/tests/MongoDB.Driver.Tests/Specifications/server-selection/
These exercise the state machines end-to-end. See the spec-conformance AGENTS.md.
Boundaries
- vs
Core/(transport/SDAM). This layer asks for a server via a binding and uses the channel handed back. Never opens or pools connections directly. - vs
Driverroot (aggregation fluent / change streams / sessions). The root surface is the public API; this layer is the engine. Operation classes underCore/Operations/are mostlyinternal sealed; a few are non-sealed where derivation is intentional (AsyncCursor<T>isinternal class;EndTransactionOperationisinternal abstractwithCommitTransactionOperation/AbortTransactionOperationderiving from it). The operation interfaces (IReadOperation<TResult>,IWriteOperation<TResult>,IExecutableInRetryableReadContext<TResult>,IExecutableInRetryableWriteContext<TResult>) are also allinternal.Core/Bindings/, however, contains several public types —CoreSession,CoreTransaction,CoreTransactionState,CoreSessionHandle,ICoreSession,ICoreSessionHandle,WrappingCoreSession,NoCoreSession,CoreSessionOptions,ICoreServerSession— so changes there are SemVer-sensitive. Other parts ofCore/also expose public types — seeCore/AGENTS.md. - vs
Authentication/. Auth happens during connection establishment in the transport layer; operations don't authenticate per-op.
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.

