mongo-csharp-driver / Linq
AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub
Translates C# Expression trees from IQueryable<T> into MongoDB aggregation pipelines. The current implementation is Linq3; Linq2 is gone. Subdirectory layout:
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/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/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
3 rules. About 0 are common, 0 are distinctive, and 3 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.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 61
Add a MethodInfo constant in Reflection/<Family>Method.cs — EnumerableMethod/QueryableMethod for BCL methods, …
- Very specific: line 64
Add a Jira-style integration test under tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/ asserting the rendered pipeline.
- Very specific: line 72
Call query.ToString() on the queryable — it renders the resulting pipeline (or, on unsupported nodes, may throw …
≈ “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
LINQ Provider — AGENTS.md
Translates C# Expression trees from IQueryable<T> into MongoDB aggregation pipelines. The current implementation is Linq3; Linq2 is gone. Subdirectory layout:
- Top-level — split by visibility:
- Public surface:
MongoQueryable,MongoEnumerable,IMongoQueryProvider,ExpressionNotSupportedException. - Internal helpers that live alongside it:
LinqProviderAdapter(internal static) and the internal forwarderIMongoQueryableForwarder<TOutput>used by it. - Concrete
IQueryable<T>implementation:MongoQuery<TDocument, TOutput> : MongoQuery<TOutput>, IOrderedQueryable<TOutput>, IAsyncCursorSource<TOutput>, IMongoQueryableForwarder<TOutput>— withMongoQuery<TOutput>as aninternal abstractbase. Both live atLinq3Implementation/MongoQuery.cs, not at the top level despite their conceptual centrality. TheIAsyncCursorSource<TOutput>implementation is what makesToList/ToCursorwork directly on the query — see the terminals discussion below.
- Public surface:
Linq3Implementation/— the engine; everything below.
Pipeline at a glance
LINQ Expression Tree
│
▼ PartialEvaluator (closures → constants)
▼ LinqExpressionPreprocessor (normalize)
▼ ExpressionToPipelineTranslator (per-method translators)
▼ ExpressionToFilterTranslators (for $match)
▼ ExpressionToAggregationExpressionTranslators (for fields/exprs)
▼ ExpressionToSetStageTranslators (for $set)
▼ AstPipeline (internal AST: Stages, Expressions, Filters)
▼ AstPipelineOptimizer (combine, hoist)
▼ Render → BsonDocument[] (the final pipeline)
▼ ExecutableQuery + IExecutableQueryFinalizer (terminal)
▼ IMongoCollection.Aggregate / AggregateAsync (which then constructs AggregateOperation / AggregateToCollectionOperation under Core/Operations)Key directories under Linq3Implementation/
Translators/— the transformation engine. Subdirectories by translation phase:ExpressionToPipelineTranslators/— top-level method calls (Where,Select,GroupBy,OrderBy,Lookup,SelectMany,Skip,Take,Distinct) →$match/$project/$group/$sort/etc.ExpressionToFilterTranslators/— predicate expressions inside$match.ExpressionToAggregationExpressionTranslators/— anything inside lambdas (binary ops, method calls, member access,new {…}).ExpressionToExecutableQueryTranslators/+Finalizers/— terminal-method handling. Three things to know:- Dispatched terminals. Currently dispatched by method name:
First,FirstOrDefault,Single,SingleOrDefault,Count,LongCount,Any,All,Contains,Sum,Average,Min,Max,Last,ElementAt, and their*Asyncvariants. Treat this list as illustrative, not authoritative — terminals are added over time; the source of truth is the dispatcher itself underExpressionToExecutableQueryTranslators/. Dispatch and runtime support are different things: some of these (notablyLastandElementAt) translate only when the source has an ordered cursor; in other shapes they throwExpressionNotSupportedExceptionat execution time. - Shared finalizers. The
Finalizers/folder holds the four shared finalizersFirstFinalizer,FirstOrDefaultFinalizer,SingleFinalizer,SingleOrDefaultFinalizer. Most other terminal translators also use anIExecutableQueryFinalizer, either by reusing one of those shared finalizers (e.g.CountMethodToExecutableQueryTranslatorreusesSingleOrDefaultFinalizer<int>) or by defining a private inline finalizer in their own translator file. ToList/ToCursorexception. Neither is in this dispatcher. They are cursor-source terminals onMongoQuery<TDocument, TOutput>itself (viaIAsyncCursorSource<TOutput>) and on theIAsyncCursorSourceExtensionsstatic class — they do not flow throughExpressionToExecutableQueryTranslator.Translate.
- Dispatched terminals. Currently dispatched by method name:
ExpressionToSetStageTranslators/— for the$setaggregation stage.
Ast/— internal AST. Three node families:Stages/— pipeline stages (non-exhaustive:AstMatchStage,AstProjectStage,AstGroupStage,AstLookupStage,AstGraphLookupStage,AstUnwindStage,AstFacetStage,AstSetWindowFieldsStage,AstDensifyStage, …)Expressions/— aggregation expressions (AstFieldPathExpression/AstGetFieldExpressionfor field references,AstConstantExpression,AstBinaryExpression,AstFunctionExpression, date/string/array operations)Filters/—$matchfilter AST. Top-level filter shapes (AstAndFilter,AstOrFilter,AstFieldOperationFilter, …) compose with per-operator nodes whose names follow the*FilterOperationconvention (AstComparisonFilterOperation,AstInFilterOperation,AstRegexFilterOperation, …).- Plus
Optimizers/andVisitors/for rewriting.
Serializers/— projection-output serializers. Two of them —IEnumerableSerializer<TItem>andIGroupingSerializer<TKey, TElement>— areinternal classes whose names happen to start withI, not interfaces. Other serializers here includeDictionarySerializer,NestedAsOrderedQueryableSerializer, andConvertIntegralTypeToEnumSerializer. The client-side projection helpers live elsewhere:ClientSideProjectionDeserializer<,>is at the public root (src/MongoDB.Driver/), and the in-LINQ helper isClientSideProjectionHelperunderLinq3Implementation/Misc/.SerializerFinders/—SerializerFinderVisitorwalks lambda bodies to infer the right serializer for the projection result. Per-node visit logic is split across files namedSerializerFinderVisit<Node>.cs(e.g.SerializerFinderVisitMethodCall.cs,SerializerFinderVisitMember.cs); theSerializerFinderVisitMethodCall.csfile tends to be the large one because it knows about every supported MongoDB LINQ extension.Reflection/— reflection-metadata constants for recognized members. Three file shapes:<Family>Method.csfiles holdMethodInfoconstants (the vast majority);<Family>Constructor.csfiles (e.g.DateTimeConstructor.cs,EnumerableConstructor.cs) holdConstructorInfoconstants;<Family>Property.csfiles (e.g.StringProperty.cs,DateTimeProperty.cs) holdPropertyInfoconstants. The framework families (EnumerableMethod,QueryableMethod,StringMethod,DateTimeMethod,MathMethod, …) sit alongside the driver-extension families that most new translators end up needing:MongoQueryableMethod/MongoEnumerableMethodhost the driver-only LINQ-operator method infos (e.g.Documents/$documents,Densify*/$densify,Lookup*overloads);LinqExtensionsMethodhosts theLinqExtensionshelpers;MqlMethodis the narrow set ofMql.*helpers (Exists,Field,IsMissing, etc.) for use inside expression bodies. Translators dispatch by reference-equality on these constants. When adding recognition for a new constructor or property, put it in the corresponding*Constructor.cs/*Property.csfile — don't invent a parallel scheme.Misc/— utilities:PartialEvaluator(closure capture),LinqExpressionPreprocessor,ConvertHelper,DocumentSerializerHelper,ExpressionReplacer,NameGenerator(for unique aggregation variable names like_v0),SymbolTable(the variable-binding scope referenced in the Variable scoping pitfall below).
And the file most translator work touches (a single class, not a directory): Linq3Implementation/Translators/TranslationContext.cs — carries serializers, translation options, and a SymbolTable (with a NameGenerator) representing the current variable-binding scope. The single most important type to understand for translator work.
Adding support for a new operator/method
- Add a
MethodInfoconstant inReflection/<Family>Method.cs—EnumerableMethod/QueryableMethodfor BCL methods,MongoQueryableMethod/MongoEnumerableMethod/LinqExtensionsMethod/MqlMethodfor driver-only methods. - For expression-level operators (used inside lambdas, e.g.
Select,Where): create a translator inTranslators/ExpressionToAggregationExpressionTranslators/MethodTranslators/<NewMethod>MethodToAggregationExpressionTranslator.cs(theMethodToAggregationExpressionTranslatorsuffix is the established convention — match it so the dispatcher's grep-by-name search finds it). Then add acase "<MethodName>": return …branch in theswitch (expression.Method.Name)block inTranslators/ExpressionToAggregationExpressionTranslators/MethodCallExpressionToAggregationExpressionTranslator.cs— this dispatcher edit is required; without it the method is unreachable. (That guidance reflects the dispatcher's currentswitch-on-name shape; if a future refactor converts it to a dictionary lookup or attribute-based registration, check the file before assuming this exact step still applies.) The per-method translator body should follow an existing method's pattern, but that's about body shape, not about whether you need the dispatch edit. The top-level dispatch is by method name; the per-method translators then verify theMethodInfomatches the canonical constants fromReflection/. - For pipeline-level operators (top-level LINQ methods like
Where,GroupBy,Skip): create a translator underExpressionToPipelineTranslators/instead and register it in the pipeline-level dispatcherExpressionToPipelineTranslator.Translate(theswitchonMethod.Nameat the top of that file). - Add a Jira-style integration test under
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/asserting the rendered pipeline.
Custom serializers in projections
If a Select produces a custom type, the SerializerFinder must know how to materialize it. Either register the serializer globally (BsonSerializer.RegisterSerializer(...)) or rely on class-map auto-mapping. For complex projections that cannot be expressed server-side, the finder falls back to ClientSideProjectionHelper — the $project includes all needed fields, and final shaping happens in the client.
Debugging a translation
- Call
query.ToString()on the queryable — it renders the resulting pipeline (or, on unsupported nodes, may throwExpressionNotSupportedExceptioncarrying the offending sub-expression). IMongoQueryProvider.LoggedStages(populated after the query executes — returnsnullbefore execution) returns the rendered stages. The same property is also exposed directly onMongoQuery<TDocument, TOutput>, so you can read it off the query without anIMongoQueryProvidercast.- For deeper debugging, set a breakpoint in
ExpressionToPipelineTranslator.Translateand inspectTranslationContext(variable bindings, scope, current serializer). ExpressionNotSupportedExceptioncarries the offending sub-expression — read the message, not just the stack.
Common pitfalls
- Closure capture.
PartialEvaluatorevaluates closures to constants before translation. If it misses one, the translator sees aMemberExpressionit can't translate. Most fixes go inPartialEvaluatoritself (aninternal static classwhose work is done by twoprivate classnestedExpressionVisitors —NominatorandSubtreeEvaluator), not the translator. - Projection vs document serialization are different. A
Select(x => x.Name)projection emits astringto BSON, not aPerson { Name = "…" }wrapper. TheSerializerFinderinfers this; manually-registered serializers can break it if they assume document context. - Variable scoping.
SelectMany,GroupBy, and$lookupintroduce nested scopes.TranslationContext.SymbolTable(seeMisc/SymbolTable.cs) is the stack-shaped scope — check it when a translator misroutes a field reference. - Reference-equality on
MethodInfo. Open vs constructed generic methods compare unequal. Translators rely on the canonicalMethodInfoconstants fromReflection/— always dispatch through those. - Async vs sync terminals. For dispatched terminals (
First/FirstAsync,Single/SingleAsync, etc.) the sync and async sides route through the sameExpressionToExecutableQueryTranslatorand, where applicable, parallelFinalizers/files for the sync vs*Asyncshape — translation is shared, finalization is per-variant.ToList/ToListAsyncandToCursor/ToCursorAsyncare not in that dispatcher at all; they go throughIAsyncCursorSourceExtensionson top of the same underlying cursor. Either way: don't add behavior to one variant without the other. ExpressionTranslationOptions. Two flags:CompatibilityLevel(typedServerVersion?; targets a specific server version's translation behavior, andnull— the default — means "current driver behavior, no version-specific compatibility shim"; the legal non-null values are the members of theServerVersionenum atsrc/MongoDB.Driver/ServerVersion.cs), andEnableClientSideProjections(typedbool?; allow falling back to client-side post-projection —null= inherit driver default). When a previously-failing expression suddenly translates — or vice versa — check whether one of these changed.ToString()reflects intent, not execution.query.ToString()renders the pipeline; running the query may still fail at execution time on server-side validation.- Constant quoting is centralized in
AstConstantExpression.Render(). A constant is wrapped in$literalwhenever its value contains something the server would reinterpret as an expression — a$-prefixed string (field path or variable) or a$-prefixed document element name (operator) — at any depth inside documents and arrays. Constants routinely carry user data (PartialEvaluatorfolds closure-captured objects, dictionaries, and arrays into aConstantExpression), so leaving one unquoted lets a$-prefixed string read a field the query never asked for. Don't add a second quoting step:ProjectionHelper.QuoteIfNecessarydeliberately skips values that already quote themselves and covers only the extra$project-specific cases (booleans, numbers, plain documents — which the server would otherwise read as include/exclude specifications). - Field names cannot be quoted — validate them instead.
$literalprotects a constant value, but an element name is emitted into the pipeline verbatim, so anywhere a field name comes from application data it must be checked withAstFieldName.IsSafe(rejects empty,$-prefixed and dotted names). Two places take a name from a folded constant:NewBsonDocumentExpressionToAggregationExpressionTranslatorthrowsExpressionNotSupportedExceptionfor an unsafe name, andAstSimplifier's$arrayToObjectrewrite only promotes akconstant to an element name when it is safe — otherwise it leaves$arrayToObjectin place, where the key stays data. Adding a new translator that builds anAstComputedFieldfrom user-supplied text needs the same check. - The query language has no
$literal. In a$match/Findfilter a document whose first element name starts with$is a set of operators, and there is no escape. That is whyAstSimplifierrefuses to collapse an$eqwhose value is such a document down to an implied operation — the explicit$eqis what keeps it a value comparison. Both predicates that feed anAstImpliedOperationFilterOperationguard against it viaAstImpliedOperationFilterOperation.CanRepresent, and that node's constructor throws as a last line of defense if a rewrite ever forgets:IsFieldEqValue({ field : { $eq : value } }→{ field : value }) andIsFieldElemMatchEqValue({ field : { $elemMatch : { $eq : value } } }→{ field : value }).IsFieldNotElemMatchEqValuedeliberately does not — it rewrites to an explicit{ field : { $ne : value } }, where the value stays an operand and is never read as operators. Don't "simplify" an$eqwrapper away, and apply the same check to any new rewrite that promotes a value to an implied operation.
How to test
Most LINQ tests assert the rendered pipeline rather than executing against a server:
dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
--filter "FullyQualifiedName~MongoDB.Driver.Tests.Linq.Linq3Implementation"Pattern (new tests): extend LinqIntegrationTest<TFixture> with a MongoCollectionFixture, build a queryable, call Translate(...), then AssertStages(stages, "{ $match: { ... } }", "{ $project: { ... } }"). Linq3IntegrationTest is the older base class still used by the existing test corpus — read it to understand the legacy pattern, but use the fixture-based LinqIntegrationTest<TFixture> for anything new. Hundreds of tests under Linq/Linq3Implementation/Jira/ follow this pattern — read 2-3 before writing a new one.
Boundaries
- vs Aggregation fluent (
src/MongoDB.Driver/Aggregate*.cs). Both produce pipelines; LINQ generates them from expression trees, fluent generates them from explicit stage calls. Both bottom out atAggregateOperationindirectly — LINQ routes throughMongoQueryProvider→IMongoCollection.Aggregate, which constructs the operation. Translators may borrowPipelineDefinition/PipelineStageDefinitiontypes but never bypass them. - vs
Bson/Serialization. LINQ relies on the registeredIBsonSerializer<T>for every materialized field; bugs frequently sit at the boundary (e.g., enum representation, custom converters). - vs
Core/Operations. LINQ stops at the rendered BSON pipeline. Cursor lifecycle, retry, and read-binding are owned by the operations layer — never call them directly.
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.

