使用Golang和MongoDB进行按字母顺序排序,并结合skip和limit使用。

huangapple go评论107阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年7月13日 17:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/45077177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定