【问题标题】:Get generated script in MongoDB C# driver在 MongoDB C# 驱动程序中获取生成的脚本
【发布时间】:2015-09-16 18:21:59
【问题描述】:

我正在使用 MongoDB.Driver 2.0.0。 有什么方法可以查看从 linq 到 MongoDB 的生成脚本?

例如我的查询是这样的:

IFindFluent<ProductMapping, ProductMapping> findFluent = Collection.Find(
    x => hashValues.Contains(x.UrlHash) && x.ProductTopic == topicId);

在 MongoDB shell 中如何表示这个(或更复杂的查询)?

【问题讨论】:

    标签: c# .net mongodb mongodb-.net-driver mongodb-csharp-2.0


    【解决方案1】:

    编辑:从驱动程序的 2.0.1 版本开始,从 IMongoCollection.Find 返回的 FindFluent 对象具有适当的 ToString,其中包括过滤器,还有投影、排序等(如果相关)。

    所以,对于这个:

    var findFluent = collection.
        Find(x => hashValues.Contains(x.UrlHash) && x.ProductTopic == topicId,
            new FindOptions {MaxTime = TimeSpan.FromSeconds(1)}).
        Project(x => x.UrlHash).
        Sort(Builders<ProductMapping>.Sort.Descending(x => x.ProductTopic)).
        Skip(6).
        Limit(7);
    
    Console.WriteLine(findFluent);
    

    输出将是:

    find({ "UrlHash" : { "$in" : [4, 5, 6, 7, 8] }, "ProductTopic" : 200 }, { "UrlHash" : 1, "_id" : 0 }).
    sort({ "ProductTopic" : -1 }).
    skip(6).
    limit(7).
    maxTime(1000)
    

    好吧,您已经知道您正在执行查找,所以我假设您想知道查询的样子。

    您可以使用 IFindFluent.Filter 直接在您的代码中轻松地做到这一点:

    BsonDocument filterDocument = findFluent.Filter.Render(
        collection.DocumentSerializer,
        collection.Settings.SerializerRegistry);
    
    Console.WriteLine(filterDocument);
    

    您的情况下的输出(当然取决于hashValuestopicId):

    { "UrlHash" : { "$in" : [4, 5, 6, 7, 8, 9] }, "ProductTopic" : 200 }
    

    【讨论】:

      【解决方案2】:

      编辑

      请参阅 i3arnon 对使用 Render() 的客户端方法的回答,这通常更容易。


      您可以使用integrated mongodb profiler 查看数据库实际收到的内容:

      db.setProfilingLevel(2); // log every request
      
      // show the requests that mongodb has received, along with execution stats:
      db.system.profile.find().pretty() 
      

      或者,您可以单步执行驱动程序的源代码并等待它实际创建消息。但是,这需要从源代码 AFAIK 编译驱动程序。

      【讨论】:

        猜你喜欢
        • 2012-03-08
        • 2015-06-09
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 2019-03-23
        相关资源
        最近更新 更多