mongodb中的分页避免skip()和limit() [英] pagination in mongodb avoid skip() and limit()
问题描述
我是nodejs的新手,我想搜索大数据,如何在不使用skip()和limit()的情况下搜索文档,我的数据库结构是
i am new in nodejs, i want to search in big data, how can i search a document without using skip() and limit(), my database structure is
{
"_id" : ObjectId("5a9d1836d2596d624873c84f"),
"updatedAt" : ISODate("2018-03-05T10:13:10.248Z"),
"createdAt" : ISODate("2018-03-05T10:13:10.248Z"),
"phone" : "+92333333",
"country_code" : "+92",
"verified_user" : false,
"verification_code" : "2951",
"last_shared_loc_time" : ISODate("2018-03-05T10:13:10.240Z"),
"share_loc_flag_time" : ISODate("2018-03-05T10:13:10.240Z"),
"share_location" : true,
"deactivate_user" : false,
"profile_photo_url" : null,
"__v" : 0
}
如何使用createdAt搜索. 我需要一个mongodb查询,该查询请求api并显示用户
how can i search using createdAt. i need a mongodb query, which request to api and show that users
推荐答案
当我们在MongoDB中拥有大数据时,建议不要使用skip()
,因为始终要求服务器从集合的开始就走,您可以使用limit()
进行分页,因为默认情况下MongoDB中对_id
字段进行了索引,因此您可以使用此字段获得良好的性能.
Using skip()
is not recommended when we have big data in MongoDB because always requires the server to walk from the beginning of the collection, you can use _id
index with limit()
to do pagination, because _id
field is indexed by default in MongoDB so you can use this field for a good performance.
对于第一页,您需要使用limit()
获取最后一个文档的_id
值:
For the first page you need to get _id
value of the last document with limit()
:
db.users.find().limit(8);
last_id = id;
第二页,将下一个_id
值与下一个_id
进行比较:
Secondly for the next page compare this last _id
value with next _id
:
db.users.find({'_id' > last_id}).limit(8);
例如,假设第一个_id
等于1000
,则:
For example assuming first _id
equal to 1000
so :
1000 < 1008 ==> PAGE 1 where last_id=1008
1008 < 1016 ==> PAGE 2 where last_id=1016
1016 < 1024 ==> PAGE 3 where last_id=1024
这篇关于mongodb中的分页避免skip()和limit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!