mongo-csharp-driver / MongoDB.Bson
AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub
The BSON library: object model, binary/JSON I/O, and the serialization framework. Foundation for everything else in the driver. Three primary subdirectories partition the work cleanly (additional folders like Exceptions/ and various top-level files — BsonExtensionMethods.cs, BsonUtils.cs, etc. — also live here):
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
In this repository35 other files it gives its agents.
- 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/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
Files
MongoDB.Bson — AGENTS.md
The BSON library: object model, binary/JSON I/O, and the serialization framework. Foundation for everything else in the driver. Three primary subdirectories partition the work cleanly (additional folders like Exceptions/ and various top-level files — BsonExtensionMethods.cs, BsonUtils.cs, etc. — also live here):
ObjectModel/— theBsonValuehierarchy and value typesIO/— readers, writers, byte buffers, JSON tokenizationSerialization/—IBsonSerializer<T>, class maps, conventions, attributes, type-specific serializers
Object model
- Immutability is split.
BsonValueitself is abstract; leaf primitives (BsonInt32,BsonString,BsonDouble,BsonBoolean,BsonObjectId,BsonDecimal128, …) are immutable. Containers (BsonDocument,BsonArray) are mutable.RawBsonDocument/RawBsonArrayare fully immutable wrappers over a raw byte buffer — prefer them for read-heavy paths where allocation matters. - Document structure.
BsonDocumentkeeps an orderedList<BsonElement>and lazily builds a name → index dictionary once the element count reaches__indexesThreshold(currently 8; seeBsonDocument.cs). Insertion order is preserved. - Duplicate names. With
AllowDuplicateNames = false(default), adding an existing name throws. With it true, only the first occurrence is reachable by name; later duplicates are accessible only by integer index. Avoid relying on duplicates. ObjectIdgeneration is spec-compliant: 4-byte timestamp + 5-byte process-scoped random (computed once at static-init — the same 5 bytes are embedded in everyObjectIdproduced by this process; they do not vary per ID) + 3-byte counter (Interlocked.Increment(ref __staticIncrement) & 0x00ffffff). SeeObjectId.csfor the per-TFM seeding details if you're auditing the RNG.ObjectIdis not cryptographic. Backed bySystem.Random(not a cryptographic RNG). If you need cryptographically unpredictable identifiers, mint them outsideObjectId.Decimal128↔ .NETdecimalis lossy in both directions: .NETdecimalhas a 96-bit mantissa (with sign + scale) inside a 128-bit representation, whileDecimal128is IEEE 754-2008 decimal128 (34 significant decimal digits). Conversions outside the .NETdecimalrange overflow. When precision matters, stay inDecimal128end-to-end.BsonTimestamp≠BsonDateTime. Timestamp is the oplog/replication metadata type (BSON type 17); DateTime is BSON type 9. They sort differently, mean different things, and are easily confused.- Binary subtypes.
BsonBinaryDatacarries a subtype byte. The legacyGuidRepresentationMode.V2switch (and its accompanying global default) has been removed in this driver — there is no global GUID-representation default any more (see GUID notes below). The on-the-wire subtype is whatever the per-serializer / per-propertyGuidRepresentationresolves to:Standardmaps to subtype 4 (new code); the legacyCSharpLegacy,JavaLegacy,PythonLegacyall map to subtype 3 (backward-compat reads).
I/O
- Reader/writer state machines.
IBsonReader/IBsonWriterenforce strict state transitions (BsonReaderState,BsonWriterState); calling out-of-order methods throwsInvalidOperationException. When stuck, read the state — not the value. BsonBinaryReader/BsonBinaryWritertrack positions on the underlyingBsonStream. Documents are length-prefixed; truncated buffers throw rather than silently succeed. There is no resync.- JSON I/O.
JsonReaderauto-detects extended JSON (e.g.,{"$oid": "..."});JsonWriteremits in the configuredJsonOutputMode(Shell,CanonicalExtendedJson,RelaxedExtendedJson). UseCanonicalExtendedJsonfor round-trip;Shellis for human REPL output and is not parsed back losslessly. - Buffer ownership.
IByteBufferandBsonChunkPooloperate by acquire/release contract. If you didn't allocate the buffer, don't dispose it. CustomStreamadapters that bypass the pool will leak.
Serialization framework
This is where most newcomer mistakes live.
IBsonSerializer<T>is required. Implement the generic interface, not just the non-genericIBsonSerializer. Many internal lookups cast toIBsonSerializer<T>and fail without it. Inherit fromSerializerBase<T>— it gives youSerialize(BsonSerializationContext, BsonSerializationArgs, T)andDeserialize(BsonDeserializationContext, BsonDeserializationArgs)to override.Registry resolution.
BsonSerializer.LookupSerializerdelegates toBsonSerializerRegistry.GetSerializer. The shape:- Cache. A single
ConcurrentDictionarycache populated via_cache.GetOrAdd(type, _createSerializer). Explicit registrations (BsonSerializer.RegisterSerializer(...)) and provider-produced serializers share that cache — there is no two-tier "explicit, then providers" lookup; explicit registrations win only becauseRegisterSerializerinserts the entry directly before any provider gets asked. - Default provider order (LIFO). On a cache miss,
CreateSerializerwalks theConcurrentStack<IBsonSerializationProvider>and returns the first non-null result. Because it's a stack, iteration is LIFO over registration order. The seven default providers are pushed byBsonSerializer's static constructor in this order:BsonClassMapSerializationProvider,DiscriminatedInterfaceSerializationProvider,CollectionsSerializationProvider,PrimitiveSerializationProvider,AttributedSerializationProvider,TypeMappingSerializationProvider,BsonObjectModelSerializationProvider— soBsonObjectModelSerializationProvideris consulted first andBsonClassMapSerializationProvideris consulted last. This list doubles as a spec — verify againstBsonSerializer's static constructor before relying on the exact order, since a future reorder there will silently rot this list. - User-registered providers. Pushed on top of that stack via
BsonSerializer.RegisterSerializationProvider, so they are consulted before any of the defaults.
Discriminators are consulted by polymorphic class-map serializers, not by the top-level lookup — read
BsonSerializerRegistry,BsonSerializer, and the providers underSerialization/Serializers/if precise ordering matters.- Cache. A single
BsonClassMapauto-maps on first use of a CLR type. After the map is frozen (automatically on first serialize, or viaFreeze()), mutation throws. The classic bug is callingBsonClassMap.RegisterClassMap<T>(...)after aThas already been auto-mapped — you must register before the type is first serialized.BsonMemberMapcontrols element name, default value, ignore-if-null/default, BSON representation, and per-member custom serializer.- Conventions.
ConventionRegistrymaps aType(or filter predicate) to aIConventionPack— an ordered list of conventions applied during auto-mapping byConventionRunner(seeSerialization/Conventions/ConventionRunner.cs). The__defaults__and__attributes__packs are registered separately and merged byConventionRegistry.Lookupinto one ordered combined pack returned to the runner. The default packs (seeConventionRegistry.csandDefaultConventionPack) put the attribute conventions last in that combined order, so attributes win any conflict — it's an ordering effect within the merged pack, not "conventions first, then attributes." Register custom packs (with a filter and name) once at startup, before any serialization. Note:ConventionRegistrysynchronizes its merge with a privatelock (__lock)rather than going throughBsonSerializer.ConfigLock(see the threading section below); registration paths in the two areas are coordinated by their own locks, not a single global lock. - Attributes.
[BsonElement],[BsonIgnore],[BsonRepresentation],[BsonDefaultValue],[BsonId],[BsonExtraElements],[BsonDiscriminator],[BsonGuidRepresentation](the actual attribute type isBsonGuidRepresentationAttributeinSerialization/Attributes/; sets per-property GUID representation and overrides any class-level or serializer-level setting — there is no global mode any more, see below). This list is illustrative, not exhaustive — seeSerialization/Attributes/for the full set (e.g.[BsonRequired],[BsonIgnoreIfDefault],[BsonIgnoreIfNull],[BsonDateTimeOptions],[BsonTimeSpanOptions],[BsonNoId],[BsonConstructor],[BsonFactoryMethod],[BinaryVector]). Bind at class-map freeze time. - Polymorphism. Discriminators land in the
_tfield by default. Use[BsonDiscriminator(RootClass = true, Required = true)]on the abstract base, and[BsonKnownTypes(typeof(SubA), typeof(SubB))]to make the subtypes register on first lookup. Without knowing about a concrete type, the deserializer can't materialize it. Security: when deserializing untrusted BSON into open polymorphic types, an attacker-controlled_tvalue can drive instantiation of any registered known type.[BsonKnownTypes]is one path that pre-registers concrete subtypes; the other isDiscriminatedInterfaceSerializationProvider, which resolves an interface-typed member to a concrete subtype based on the wire_tvalue at deserialization time — both ride on the same discriminator lookup, and both should be limited to subtypes you actually intend to accept. [BsonExtraElements]is the forward-compat escape hatch: aDictionary<string, object>(orBsonDocument) member that absorbs unknown fields. Without it, schema evolution on the server side breaks the client immediately.
Guid representation
Long-running migration. There is no global GUID representation mode any more — the legacy GuidRepresentationMode.V2 / V3 switch was removed, and representation must always be chosen per-serializer or per-property. GuidSerializer requires an explicit GuidRepresentation; constructing one with GuidRepresentation.Unspecified (or leaving a Guid property without an explicit representation) succeeds at construction time, but its Serialize / Deserialize methods throw BsonSerializationException on the first call.
For new code, do one of:
- Decorate
Guidproperties with[BsonGuidRepresentation(GuidRepresentation.Standard)](subtype 4, bytes in RFC 4122 order — the in-memoryGuidmixed-endian byte order is normalized at serialize time), or - Register
new GuidSerializer(GuidRepresentation.Standard)per type.
The common silent-corruption mode is mismatched GuidRepresentation across serializers — e.g. one service writes with Standard, another reads with CSharpLegacy, or a discriminator-selected polymorphic path picks a different representation than the writer. Anything reading documents written by older C# drivers may need CSharpLegacy; cross-language deployments need Standard.
Threading & lifecycle
- BSON serialization is thread-safe for steady-state reads.
BsonSerializerRegistryitself is backed by aConcurrentDictionaryplus aConcurrentStackof provider lookups, so cache-hit lookups are lock-free. Cache misses still enter the provider-walk path and may trigger class-map freezing underBsonSerializer.ConfigLock— that's aReaderWriterLockSlimthat broadly coordinates config-time state acrossBsonSerializer(class-map freezing and serializer registration, plus discriminator-convention lookup, known-type registration, and assorted deserialization helpers all enter it). Treat it as the shared config-time lock, not a registration-only lock. - Class maps and member maps freeze on first use. Configuration must happen at startup before anything is serialized.
- For very large documents, prefer
BsonBinaryReader/BsonBinaryWriterover a stream rather than materializing asBsonDocument.
Common pitfalls
- Implementing only the non-generic
IBsonSerializer— typed lookups (BsonSerializerRegistry.GetSerializer<T>) do a hard cast toIBsonSerializer<T>and throwInvalidCastExceptionrather than silently falling back. - Calling
RegisterClassMap<T>afterTwas auto-mapped — throws. - Mixing attributes and explicit class-map registration without realizing attributes win at conflict (because
AttributeConventionPackruns last in the default packs). - Mismatched
GuidRepresentationacross services / serializers — round-trips silently corrupt;Unspecifiedthrows. - Decimal128 → .NET decimal precision loss / overflow.
- Forgetting
[BsonExtraElements]; client breaks the moment the server adds a field. - Forgetting to register a discriminator — polymorphic deserialization throws "no concrete type" at runtime, not compile.
- Mutating a frozen class map (e.g., late convention registration in test setup).
- Disposing a pooled
IByteBufferyou didn't acquire — corrupts the pool.
How to test
dotnet test tests/MongoDB.Bson.Tests/MongoDB.Bson.Tests.csproj -f net10.0Single-area filters:
dotnet test tests/MongoDB.Bson.Tests/MongoDB.Bson.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~ObjectModel"
dotnet test tests/MongoDB.Bson.Tests/MongoDB.Bson.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Serialization"
dotnet test tests/MongoDB.Bson.Tests/MongoDB.Bson.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~Jira" # regression testsBSON corpus / spec tests are JSON-driven via the runner under tests/MongoDB.Driver.Tests/Specifications/bson-corpus/ (the runner lives in the Driver test project, not in tests/MongoDB.Bson.Tests/) and exercise the canonical, relaxed, and degenerate JSON forms across BSON types.
Spec links
- BSON spec:
https://bsonspec.org/ - Extended JSON / BSON corpus runner:
tests/MongoDB.Driver.Tests/Specifications/bson-corpus/
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.

