#Introducing the MongoDB Analyzer for .NET
Correct code culprits at compile time!
As C# and .NET developers, we know that it can sometimes be frustrating to work idiomatically with MongoDB queries and aggregations. Without a way to see if your LINQ query or Builder expression corresponds to the MongoDB Query API (formerly known as MQL) during development, you previously had to wait for runtime errors in order to troubleshoot your queries. We knew there had to be a way to work more seamlessly with C# and MongoDB.
That’s why we’ve built the MongoDB Analyzer for .NET! Instead of mentally mapping the idiomatic version of your query in C# to the MongoDB Query API, the MongoDB Analyzer can do it for you - and even provide the generated Query API expression right in your IDE. The MongoDB Analyzer even surfaces useful information and helpful warnings on invalid expressions at compile time, bringing greater visibility to the root causes of bugs. And when used together with the recently released LINQ3 provider (now supported in MongoDB C#/.NET Driver 2.14.0 and higher), you can compose and understand queries in a much more manageable way.
Let’s take a look at how to install and use the new MongoDB Analyzer as a NuGet package. We’ll follow with some code samples so you can see why this is a must-have tool for Visual Studio!
#Install MongoDB Analyzer as a NuGet Package
In Visual Studio, install the
MongoDB.Analyzer NuGet package:
1 Install-Package MongoDB.Analyzer -Version 1.0.0
1 dotnet add package MongoDB.Analyzer --version 1.0.0
Once installed, it will be added to your project’s Dependencies list, under Analyzers:
After installing and once the analyzer has run, you’ll find all of the diagnostic warnings output to the Error List panel. As you start to inspect your code, you’ll also see that any unsupported expressions will be highlighted.
#Inspecting Information Messages and Warnings
As you write LINQ or Builders expressions, an information tooltip can be accessed by hovering over the three grey dots under your expression:
Accessing the tooltip for a LINQ expression
This tooltip displays the corresponding Query API language to the expression you are writing and updates in real-time! With the translated query at your tooltips, you can confirm the query being generated (and executed!) is the one you expect.
This is a far more efficient process of composing and testing queries—focus on the invalid expressions instead of wasting time translating your code for the Query API! And if you ever need to copy the resulting queries generated, you can do so right from your IDE (from the Error List panel).
Another common issue the MongoDB Analyzer solves is surfacing unsupported expressions and invalid queries at compile time. You’ll find all of these issues listed as warnings:
Unsupported expressions shown as warnings in Visual Studio’s Error List
This is quite useful as not all LINQ expressions are supported by the MongoDB C#/.NET driver. Similarly, supported expressions will differ depending on which version of LINQ you use.
#Code Samples—See the MongoDB Analyzer for .NET in Action
Now that we know what the MongoDB Analyzer can do for us, let’s see it live!
These are a few examples that show how Builder expressions are analyzed. As you’ll see, the MongoDB Analyzer provides immediate feedback through the tooltip. Hovering over your code shows you the supported Query API language that corresponds to the query/expression you are writing.
Builder Filter Definition - Filter movies by matching genre, score that is greater than or equal to minimum score, and a match on the title search term.
Builder Sort Definition - Sort movies by score (lowest to highest) and title (from Z to A).
Unsupported Builder Expression - Highlighted and shown as warning in Error List.
The MongoDB Analyzer uses the default LINQ provider of the C#/.NET driver (LINQ2). Expressions that aren’t supported in LINQ2 but are supported in LINQ3 will show the appropriate warnings, as you’ll see in one of the following examples. If you’d like to switch the LINQ provider the MongoDB Analyzer uses, set
“DefaultLinqVersion”: “V3”in the
LINQ Filter Query - Aggregation pipeline.
LINQ Query - Get movie genre statistics; uses aggregation pipeline to group by and select a dynamic object.
Unsupported LINQ Expression - GetHashCode() method unsupported.
Unsupported LINQ Expression - Method referencing a lambda parameter unsupported.
Unsupported LINQ2, but supported LINQ3 Expression - Trim() is not supported in LINQ2, but is supported in LINQ3.
#MongoDB Analyzer + New LINQ3 Provider = 💚
If you’d rather not see those “unsupported in LINQ2, but supported in LINQ3” warnings, now is also a good time to update to the latest MongoDB C#/.NET driver (2.14.1) which has LINQ3 support! While the full transition from LINQ2 to LINQ3 continues, you can explicitly configure your MongoClient to use the new LINQ provider like so:
1 var connectionString = "mongodb://localhost"; 2 var clientSettings = MongoClientSettings.FromConnectionString(connectionString); 3 clientSettings.LinqProvider = LinqProvider.V3; 4 var client = new MongoClient(clientSettings);
#Integrate MongoDB Analyzer for .NET into Your Pipelines
The MongoDB Analyzer can also be used from the CLI which means integrating this static analysis tool into your continuous integration and continuous deployment pipelines is seamless! For example, running
dotnet build from the command line will output MongoDB Analyzer warnings to the terminal:
Running dotnet build command outputs warnings from the MongoDB Analyzer
Adding this as a step in your build pipeline can be a valuable gate check for your build. You’ll save yourself a potential headache and catch unsupported expressions and invalid queries much earlier.
Another idea: Output a Static Analysis Results Interchange Format (SARIF) file and use it to generate explain plans for all of your queries. SARIF is a standard, JSON-based format for the output of static analysis tools, making a SARIF file an ideal place to grab the supported queries generated by the MongoDB Analyzer.
To output a SARIF file for your project, you’ll need to add the
ErrorLog option to your
.csproj file. You’ll be able to find it at the root of your project (unless you’ve specified otherwise) the next time you build your project.
With this file, you can load it via a mongosh script, process the file to find and “clean” the found MongoDB Query API expressions, and generate explain plans for the list of queries. What can you do with this? A great example would be to output a build warning (or outright fail the build) if you catch any missing indexes! Adding steps like these to your build and using the information from the expain plans, you can prevent potential performance issues from ever making it to production.
#We Want to Hear From You!
With the release of the MongoDB Analyzer for .NET, we hope to speed up your development cycle and increase your productivity in three ways: 1) by making it easier for you to see how your idiomatic queries map to the MongoDB Query API, 2) by helping you spot unsupported expressions and invalid queries faster (at compile time, baby), and 3) by streamlining your development process by enabling static analysis for your MongoDB queries in your CI/CD pipelines!
We’re quite eager to see the .NET and C# communities use this tool and are even more eager to hear your feedback. The MongoDB Analyzer is ready for you to install as a NuGet package and can be added to any existing project that uses the MongoDB .NET driver. We want to continue improving this tool and that can only be done with your help. If you find any issues, are missing critical functionality, or have an edge case that the MongoDB Analyzer doesn’t fulfill, please let us know! You can alsopost in our Community Forums.