4

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?

Priyanka
  • 354
  • 7
  • 14
  • This question+answer might be of interest / value to you: [Efficient paging in MongoDB using mgo](https://stackoverflow.com/questions/40634865/efficient-paging-in-mongodb-using-mgo). – icza Jul 13 '17 at 09:55
  • So the issue is basically that `Skip` isn't working? You get the same 10 results regardless of the value of `pageNo`? – Adrian Jul 19 '17 at 15:03

2 Answers2

2

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)
}   
....
....
Keshav Lodhi
  • 2,641
  • 2
  • 17
  • 23
1

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)
Chinmaya Pati
  • 357
  • 3
  • 7