开发者

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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜