skip to Main Content

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()?

2

Answers


  1. You could follow this document to log the process of mongodriver. https://www.mongodb.com/docs/drivers/csharp/v2.25/fundamentals/logging/
    Or if you want to log only the query you could do following configuration when create client in order to see commands in console.

    var client = new MongoClient(new MongoClientSettings()
    {
        
        Server = new MongoServerAddress("127.0.0.1"),
        ClusterConfigurator = cb =>
        {
            cb.Subscribe<CommandStartedEvent>(e =>
            {
                Console.WriteLine($"{e.CommandName} - {e.Command.ToJson()}");
            });
        }
    });
    
    Login or Signup to reply.
  2. (Duplicate of) See my answer here.

    1. In 2 words, 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(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.

    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("");
      settings.LoggingSettings = new LoggingSettings(loggerFactory);
      var client = new MongoClient(settings);

    4. Collection.FindAsync(...)
      

    there is no difference here with Find. The only difference that should unwrap *Async methods via something like .GetAwaiter().GetResult().ToList().
    However, better to translate query without sending request to the server. See my answer here for more details

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search