英文:
Golang MongoDB sorting alphabetically with skip and limit
问题
我需要按字母顺序对结果进行排序,每页限制10个。但是用我的代码,我得到的结果是每页按字母顺序排列的10个,下一页的10个又从'a'开始。类似这样...我的代码如下:
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)
有没有办法先对所有结果按字母顺序排序,然后再应用分页?
英文:
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?
答案1
得分: 2
你可以使用go mongo-driver
中的options
包来实现排序、跳过和限制功能。
import (
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"context"
"log"
)
collection := mongoClient.Database("数据库名称").Collection("集合名称")
options := options.Find()
options.SetSort(bson.M{"字段名": 1})
options.SetSkip(0)
options.SetLimit(10)
cursor, error := collection.Find(context.TODO(), bson.M{}, options)
if error != nil {
log.Fatal(error)
}
....
....
英文:
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)
}
....
....
答案2
得分: 1
这应该可以工作!
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论