有没有办法记录MongoDB C#驱动程序生成的实际查询并发送到mongodb?与SQL Server一样,您可以使用SQL事件探查器向您显示所有传入的查询。
答案 0 :(得分:15)
db.setProfilingLevel(2);
答案 1 :(得分:15)
您可以启用分析并在mongodb日志中查看@ pingw33n建议的实际查询。
或者你可以为collection创建扩展方法。在那里找到并记录数据:
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);
}
}
答案 2 :(得分:0)
扩展方法@Andrew建议只适用于FIND查询。 从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()})");
}