Get generated script in MongoDB C# driver

烂漫一生 提交于 2019-12-17 19:46:10

问题


I am using MongoDB.Driver 2.0.0. Is there any way to see a generated script from linq to MongoDB?

For example my query is like:

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

How would this (or more complex queries) be represented in the MongoDB shell?


回答1:


EDIT

Please see i3arnon's answer for a client-side method using Render() that is usually easier.


You can use the integrated mongodb profiler to see what the database has actually received:

db.setProfilingLevel(2); // log every request

// show the requests that mongodb has received, along with execution stats:
db.system.profile.find().pretty() 

Alternatively, you can step in the source code of the driver and wait for it to actually create the message. That, however, requires compiling the driver from source, AFAIK.




回答2:


EDIT: As of the 2.0.1 version of the driver the FindFluent object returned from IMongoCollection.Find has an appropriate ToString that includes the filter, but also a projection, sort and so forth (if relevant).

So, for this:

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);

The output would be:

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

Well, you already know you are doing a find so I assume you want to know what the query looks like.

You can easily do that directly from your code using IFindFluent.Filter:

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

Console.WriteLine(filterDocument);

The output in your case (depends on hashValues and topicId of course):

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


来源:https://stackoverflow.com/questions/30306193/get-generated-script-in-mongodb-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!