0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang mgo でページネーション

Last updated at Posted at 2018-11-12

mgoはGoでMongoDBを扱うためのライブラリ。
これを用いてページネーションしたい。

が、いかんせんMongoDBもmgoも初めて触ったのでよくわからない。
とりあえずmgoにはページネーションのための便利関数のようなものはなさそう。
minquery というライブラリもあるようだが、 cursor の扱いが今ひとつ分からなかったのと、ごくシンプルな要件が実現できればよかったので自前実装することにした。

サンプルコードがNode.jsだが下記を参考にした。

Approach 1: Using skip() and limit() を採用。
この方式は 実装が簡単だがデータ量が増えるにつれてパフォーマンス上の問題を抱える とあるが、大したデータ量ではないのでこちらで。

サンプルコード

// 本来は引数で渡す
perPage := 10 // ページあたり件数
currentPage := 1 // 現在のページ

session, err = mgo.Dial("mongodb://mongo/test")
if err != nil {
	log.Fatalln(err)
}
db = session.DB("test")

var people []*Person

q := db.C("people").Find(bson.M{}).Skip(perPage * (currentPage - 1)).Limit(perPage)
q.All(&people)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?