14

Is there a way to log the actual queries that are produced by the MongoDB C# driver and sent to the mongodb? Like in SQL Server, you have SQL Profiler that shows you all the incoming queries.

3 Answers 3

16

You can enable profiling and see actual queries in mongodb log as @pingw33n suggested.

Or you can create extention method for collection.Find and log data there:

public static class MongodbExtentions
{
    public static MongoCursor<T> FindAsAndLogQuery<T>(this MongoCollection<T> coll, 
                                                                    IMongoQuery query)
    {
        var queryString = query.ToJson();
        //log query here , insert into mongodb, etc ...
        return coll.FindAs<T>(query);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

15
db.setProfilingLevel(2);

http://www.mongodb.org/display/DOCS/Database+Profiler

Comments

1

Extension method @Andrew suggested would only work for FIND queries. From MongoDB 3.2 you can do something like below which will work for all queries.

private static void LogQuery<TEntity>(string queryType, FilterDefinition<TEntity> filter,
            UpdateDefinition<TEntity> update, IMongoCollection<TEntity> collection)
            where TEntity : class, new()
        {
            var renderedFilter = filter.Render(collection.DocumentSerializer, collection.Settings.SerializerRegistry);
            var renderUpdate = update.Render(collection.DocumentSerializer, collection.Settings.SerializerRegistry);
            // Log you shell scrip as string to a file or DB
            Log.Debug(
                $"use {collection.Database.DatabaseNamespace.DatabaseName} db.{collection.CollectionNamespace.CollectionName}.{queryType}({renderedFilter.ToJson()},{renderUpdate.ToJson()})");
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.