Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

.net - Get generated script in MongoDB C# driver

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...