TIMEX
TIMEX

Reputation: 271594

How do I make my MongoDB query more efficient?

Right now, I'm doing 2 steps. I want to eliminate one of them.

//Get total results, before the limit. I need this number for pagination reasons.
total_rooms = db.rooms.find({'name':'big'}).count();

//Get the actual results
rooms = db.rooms.find({'name':'big'}).skip(start).limit(num)

I'm doing double queries everywhere around my website, and I feel really silly. Mysql only requires me to do one query, and gives me the total_results.

Upvotes: 1

Views: 262

Answers (1)

Remon van Vliet
Remon van Vliet

Reputation: 18595

You only need one query. Try this in the shell :

for(var i = 0; i < 1000; i++) db.test.save({a:i})
cursor = db.test.find().skip(10).limit(10)

Now, you can get the total result set size :

cursor.count()
1000

And the result set size taking skip and limit into account :

cursor.count(true)
10

Note that the server will do all the work needed to determine both numbers and a new count query will be issued if there is more data available on the server than was returned with the first results. In other words, cleaner code but not always more performance.

Upvotes: 1

Related Questions