Pagination in Golang and MongoDB - DEV Community
Pagination in Golang and MongoDB - DEV Community
MongoDB
👋 Kindness isiscontagious
a document based data store and hence pagination is one of the most
common use case of it. So when do you paginate the response? The answer is pretty
Venture
neat; youinto the heart
paginate of theyou
whenever developer world on
want to process DEVinCommunity—a
result chunks. Some common
nurturingare
scenarios zone where all coders, irrespective of their journey's stage, are
warmly invited to expand our collective tech wisdom.
Batch processing
Heartfelt
Showing“thanks” areresults
huge set of like cozy embraces—scatter
on user interfac them generously in the
comments!
Paginating on client
Your insights and server
invigorate side
DEV's are both really
experience and very expensive
amplify and should Did
our camaraderie. not be
considered. Hence pagination is generally handled at database level and databases are
this article enrich your developer life? Take a brief moment to express your
optimized for such needs to
gratitude to the author.
2 approaches through which you can easily paginate your MongoDB responses. Sample
Agreed
Document
{
"_id" : ObjectId("6936d17263623919cd5145db"),
"name" : "Neeraj Kumar",
"age" : 25
}
cursor.skip()
cursor.limit()
skip(n) will skip n documents from the cursor while limit(n) will cap the number of
documents to be returned from the cursor. Thus combination of two naturally paginates
the response.
In Mongo Shell your pagination code looks something like
// Page 1
db.students.find().limit(10)
// Page 2
db.students.find().skip(10).limit(10)
// Page 3
db.students.find().skip(10).limit(10)
👋 Kindness is contagious
implement pagination:
Venture into the heart of the developer world on DEV Community—a
nurturing zone where all coders,
func GetPagination(limit, page int)irrespective
error { of their journey's stage, are
warmly invited:=tocontext.WithTimeout(context.Background(),
ctx, cancel expand our collective tech wisdom. 12*time.Second)
defer cancel()
Heartfelt
coll := “thanks” are like cozy embraces—scatter them generously in the
o.db.Database(mongoDatabaseName).Collection(offerCollectionName)
comments!
l := int64(limit)
Your skip
insights invigorate
:= int64(page DEV's- experience
* limit limit) and amplify our camaraderie. Did
this article
fOpt :=enrich your developer life? Take
options.FindOptions{Limit: a brief&skip}
&l, Skip: moment to express your
gratitude to the author.
curr, err := coll.Find(ctx, bson.D{{}}, &fOpt)
if err != nil {
Agreed
return result, err
}
for curr.Next(ctx) {
var el Offer
if err := curr.Decode(&el); err != nil {
log.Println(err)
}
This approach will make effective use of default index on _id and nature of ObjectId. I
bet you didn’t know that a Mongodb ObjectId is a 12 byte structure containing
Using this property of ObjectId and also taking into consideration the fact that _id is
always indexed, we can devise following approach for pagination:
👋 Kindness is contagious
// Page 1
db.students.find().limit(10)
Venture into the heart of the developer world on DEV Community—a
nurturing zone
// Page 2 where all coders, irrespective of their journey's stage, are
last_id = ... # logic to get last_id
warmly invited to expand our collective tech wisdom.
db.students.find({'_id': {'$gt': last_id}}).limit(10)
for curr.Next(ctx) {
var el Offer
if err := curr.Decode(&el); err != nil {
log.Println(err)
}
👋 Before you go
Top comments
Heartfelt (0)like cozy embraces—scatter them generously in the
“thanks” are
comments!
Code of Conduct • Report abuse
Your insights invigorate DEV's experience and amplify our camaraderie. Did
this article enrich your developer life? Take a brief moment to express your
gratitude
Sentry to the author.
PROMOTED
Agreed
👋 Kindness is contagious
Fixing code“thanks”
Heartfelt doesn’t have to becozy
are like the worst part of your day.
embraces—scatter Learngenerously
them how Sentryin
can
the
help.
comments!
Your insights invigorate DEV's experience and amplify our camaraderie. Did
Learn more
this article enrich your developer life? Take a brief moment to express your
gratitude to the author.
Agreed
Neeraj Kumar
My name is Neeraj Kumar, and I have over 4 years of experience in JavaScript (Node.js), Golang, Java
(Vertx), AWS, Docker, MongoDB, PostgreSQL, MySQL, JavaScript, Data Structures and Algorithms
(DSA),
LOCATION
Bengaluru
EDUCATION
B.TECH(CSE)
WORK
Full Stack Developer
JOINED
Oct 1, 2022
What is Go?
👋 #Kindness
#go devops is contagious
#beginners
Agreed
👋 Kindness is contagious
Agreed