开发者

How to time a MongoQuery from C#

开发者 https://www.devze.com 2023-03-29 14:14 出处:网络
I try 开发者_StackOverflow中文版to timed a Mongo query in C# on a column with an index: DateTime startTime = DateTime.Now;

I try 开发者_StackOverflow中文版to timed a Mongo query in C# on a column with an index:

DateTime startTime = DateTime.Now;
MongoCollection<BsonDocument> voteCol = database.GetCollection<BsonDocument>("XXX");
var query = new QueryDocument("YYY", "23915");
MongoCursor<BsonDocument> cursor = voteCol.Find(query).SetSortOrder(SortBy.Descending("ZZZ")).SetLimit(10).SetSkip(20);
TimeSpan elapsedTime = DateTime.Now - startTime;
Console.WriteLine("Elapsed: {0}, in seconds: {1}, in milliseconds: {2} ", 
elapsedTime, elapsedTime.TotalSeconds, elapsedTime.TotalMilliseconds, cursor.Count());

Everytime it is equal to 0 and I get the results. Does it mean that it is too fast or did I missed something?


This is because you actually not loading data from mongodb. Data will be loaded when you start iterate through MongoCursor. You can easy use ToList method to load data from the database:

var data = voteCol.Find(query)
    .SetSortOrder(SortBy.Descending("ZZZ"))
    .SetLimit(10)
    .SetSkip(20)
    .ToList();

Also i suggest to use Stopwatch to evaluate elapsed time.


Like Andrew says, Mongo don't actually execute the query until you start iterating over the cursor, so your query isn't being executed.

The Stopwatch class is probably the best way to time the query from your application, but you can also benchmark your queries at the database using the MongoDB Database Profiler.


try Stopwatch

0

精彩评论

暂无评论...
验证码 换一张
取 消