【问题标题】:Mongo DB C# Driver - Getting Translated BSON from C# codeMongodb C# 驱动程序 - 从 C# 代码中获取翻译后的 BSON
【发布时间】:2013-02-22 22:04:23
【问题描述】:

假设我使用 C# 驱动程序设置了以下光标:

     var cursor = _mongoClient.GetServer()
                               .GetDatabase("test")
                                .GetCollection<BsonDocument>("somecollection")
                                .Find(Query.EQ("field", "value"))
                                .SetFields(Fields.Exclude())
                                .SetLimit(5)
                                .SetSortOrder("field");
     var results = cursor.ToList();

我想查看发送到 mongo 服务器的已翻译 BSON 命令(即“db.somecollection.find({...})”。

任何一种方式都可以接受:

1.某种将其打印为字符串的函数。

2. 某种“嗅探”发送到服务器的命令的方法。 (mongo.exe 中的 db 分析功能仅显示 where 子句和 order by --我想查看所有内容 --limit、字段投影等)

此外,使用 MongoQueryable 执行此操作也很棒。

【问题讨论】:

    标签: mongodb mongodb-.net-driver


    【解决方案1】:

    类似:

    var queryable= (MongoQueryable<BsonDocument>)someCollection;
    var debug = queryable.GetMongoQuery().ToJson();
    

    【讨论】:

    • 这只会显示可查询的“位置”部分。我想查看所有内容——位置、排序、跳过、限制、字段等。
    【解决方案2】:

    因此,看起来 MongoCursor 的序列化被封装在 MongoDB.Driver 程序集内部的类中。因此,发送到服务器的序列化 BSON 消息至少在客户端代码中是不可见的。

    但是,我可以合理地相信 MongoCursor 在较低级别被正确翻译。 (毕竟 10gen 支持这个项目。)

    更令人担忧的是如何翻译 LINQ 表达式。如果我可以验证 LINQ IQueryables 是否被转换为具有正确状态的 MongoCursor,那我就完美了。

    所以,这是一个将光标拉出 IQueryable 的扩展方法:

        public static class MongoExtensions
        {
    
           public static MongoCursor GetCursor<T>(this IQueryable<T> source)
           {
               var queryProvider = source.Provider as MongoQueryProvider;
               if (queryProvider == null)
               {
                   throw new NotSupportedException("Explain can only be called on a Linq to Mongo queryable.");
               }
    
               var selectQuery = (SelectQuery)MongoQueryTranslator.Translate(queryProvider, source.Expression);
    
               if (selectQuery.Take.HasValue && selectQuery.Take.Value == 0)
               {
                   throw new NotSupportedException("A query that has a .Take(0) expression will not be sent to the server and can't be explained");
               }
    
               var projector = selectQuery.Execute();
    
               var cursorProp = projector.GetType().GetProperties().FirstOrDefault(p => p.Name == "Cursor");
               return cursorProp.GetValue(projector) as MongoCursor<T>;
    
           }
        }
    

    然后我可以测试 MongoCursor 的状态,检查“Query”、“Skip”、“Limit”等属性以及“Options”集合中的所有项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多