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

我使用的是MongoDB.Driver 2.0.0。 有没有办法看到从linq到MongoDB生成的脚本?

例如,我的查询如下:

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

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

编辑

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


您可以使用集成的mongodb分析器来查看数据库实际收到的内容:

 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对象具有包含filter的适当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.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直接从代码中轻松完成此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 }