开发者

Profiling MongoDB queries when using C# driver

开发者 https://www.devze.com 2023-03-11 19:00 出处:网络
Is there a way to log the actual queries that are produced by the MongoDB C# driver and sent to the mongodb? Like in开发者_JS百科 SQL Server, you have SQL Profiler that shows you all the incoming quer

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


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);
    }
}


db.setProfilingLevel(2);

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


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()})");
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消