【问题标题】:Golang MongoDB sorting alphabetically with skip and limitGolang MongoDB 使用跳过和限制按字母顺序排序
【发布时间】:2017-12-18 00:46:51
【问题描述】:

我需要按字母顺序排序的结果,每页限制为 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)

有没有办法先按字母顺序对所有内容进行排序,然后再应用分页?

【问题讨论】:

  • 这个问题+答案可能会让您感兴趣/有价值:Efficient paging in MongoDB using mgo
  • 所以问题基本上是Skip 不起作用?无论pageNo 的值如何,您都会得到相同的 10 个结果?

标签: mongodb sorting go limit skip


【解决方案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)

【讨论】:

    【解决方案2】:

    使用 go mongo-driver 的 options 包可以实现排序、跳过和限制。

    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)
    }   
    ....
    ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2018-04-18
      相关资源
      最近更新 更多