Search code examples
mongodbamazon-web-servicesasp.net-coremongodb-.net-driver.net-7.0

How can I see the generated query when calling Collection.FindAsync()


You can view Collection.Find(...).ToString() in the Watch window in Visual Studio to see the generated query, but this doesn't work for Collection.FindAsync(...).

How can I see the generated query used behind the scenes when calling FindAsync()?


Solution

  • (Duplicate of): See my answer here. So you have the below options:

    1. You can subscribe on driver events, in particular CommandStartedEvent will contain information about sent commands to the server.

      var settings = MongoClientSettings.FromUrl(new MongoUrl(@"mongodb://localhost"));
      settings.ClusterConfigurator = builder =>
      {
           builder.Subscribe<CommandStartedEvent>(x =>
           {
              var queryDocument = x.Command;
           });
      };
      
      var client = new MongoClient(settings);
      
    2. Also, you can use query analyzer plugin for the driver that will allow you to see queries that will be sent to the server just in VS notes: enter image description here

    3. As additional approach, there is an option to use ILogger impls, you can find details here. Configuration will look similar to:

      using var loggerFactory = LoggerFactory.Create(b =>
      {
         b.AddSimpleConsole();
         b.SetMinimumLevel(LogLevel.Debug);
      });
      var settings = MongoClientSettings.FromConnectionString("<connection string>");
      settings.LoggingSettings = new LoggingSettings(loggerFactory);
      var client = new MongoClient(settings);
      

    but this doesn't work for Collection.FindAsync(...)

    Find (FluentAPI) and FindAsync are significantly different methods (pay attention there is a FindSync method), I'm not sure off the top of my head whether you can rely on what ToString has provided for you.

    I recommend to render your filter, ie translate your query without sending request to the server. See my answer here for more details. In short, if you have a mongo command (let's say a mongo filter or aggregate pipeline) like:

     var builder = Builders<Flower>.Filter;
     var filter = builder.Lt(f => f.Price, 20) & builder.Eq(f => f.Category, "Perennial");
    

    you can render it via:

        var registry = BsonSerializer.SerializerRegistry;
        var serializer = registry.GetSerializer<Flower>();
        var output = filter.Render(serializer, registry).ToString();
    

    output will contain generated query that driver will send to the server.