Priyanka
Priyanka

Reputation: 364

Golang MongoDB sorting alphabetically with skip and limit

I need results sorted alphabetically limiting 10 per page. But with my code, I get results as 10 per page alphabetically, next 10 again starts from 'a'. Likewise... My code is like,

pageNo := 1
perPage := 10
DB.C("collection").Find(bson.M{"_id": bson.M{"$in": ids}}).Sort("name").Skip((pageNo - 1) * perPage).Limit(perPage).All(&results)

Is there any way to sort all alphabetically first and then apply pagination?

Upvotes: 4

Views: 6331

Answers (2)

Keshav Lodhi
Keshav Lodhi

Reputation: 3182

You can achieve sorting, skip and limit by using options package from go mongo-driver.

import (
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"context"
"log"
)

collection := mongoClient.Database("name-of-the-database").Collection("name-of-the-collection")
options := options.Find()
options.SetSort(bson.M{"field-name" : 1})
options.SetSkip(0)
options.SetLimit(10)

cursor, error := collection.Find(context.TODO(), bson.M{}, options)
if error != nil {
    log.Fatal(error)
}   
....
....

Upvotes: 2

Chinmaya Pati
Chinmaya Pati

Reputation: 397

This should work!

filter := bson.M{"_id": bson.M{"$in": ids}}
skip := int64(0)
limit := int64(10)

opts := options.FindOptions{
  Skip: skip,
  Limit: limit
}

DB.C("collection").Find(nil, filter, &opts)

Upvotes: 1

Related Questions