在 MongoDB C# 驱动程序中获取生成的脚本

Get generated script in MongoDB C# driver

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

例如我的查询是这样的:

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

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

编辑

请参阅 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 编译驱动程序。

编辑:从驱动程序的 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 }