2011-06-08 93 views

回答

14

您可以启用分析,看看在MongoDB中记录的实际查询为@ pingw33n建议。

或者可以为collection.Find创建extention方法有日志数据:

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

扩展方法@Andrew建议将只在搜索内容中的查询工作。 从MongoDB 3.2开始,你可以做一些类似于下面的事情,它可以处理所有的查询。

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()})"); 
     } 
相关问题