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
精彩评论