• Stars
    star
    130
  • Rank 277,575 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang Mongodb Pagination for official mongodb/mongo-go-driver package which supports both normal queries and Aggregation pipelines with all information like Total records, Page, Per Page, Previous, Next, Total Page and query results.

Golang Mongo Pagination For Package mongo-go-driver

Workflow Build Go Report Card GoDoc Coverage Status

For all your simple query to aggregation pipeline this is simple and easy to use Pagination driver with information like Total, Page, PerPage, Prev, Next, TotalPage and your actual mongo result. View examples from here

🔈 🔈 For normal queries new feature have been added to directly pass struct and decode data without manual unmarshalling later. Only normal queries support this feature for now. Sort chaining is also added as new feature

Example api response of Normal Query click here.
Example api response of Aggregate Query click here.
View code used in this example from here

Install

$ go get -u -v github.com/gobeam/mongo-go-pagination

or with dep

$ dep ensure -add github.com/gobeam/mongo-go-pagination

For Aggregation Pipelines Query

package main

import (
	"context"
	"fmt"
	. "github.com/gobeam/mongo-go-pagination"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type Product struct {
	Id       primitive.ObjectID `json:"_id" bson:"_id"`
	Name     string             `json:"name" bson:"name"`
	Quantity float64            `json:"qty" bson:"qty"`
	Price    float64            `json:"price" bson:"price"`
}

func main() {
	// Establishing mongo db connection
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	
	var limit int64 = 10
	var page int64 = 1
	collection := client.Database("myaggregate").Collection("stocks")

	//Example for Aggregation

	//match query
	match := bson.M{"$match": bson.M{"qty": bson.M{"$gt": 10}}}

	//group query
	projectQuery := bson.M{"$project": bson.M{"_id": 1, "qty": 1}}

    // set collation if required
    collation := options.Collation{
		Locale:    "en",
		CaseLevel: true,
	}

	// you can easily chain function and pass multiple query like here we are passing match
	// query and projection query as params in Aggregate function you cannot use filter with Aggregate
	// because you can pass filters directly through Aggregate param
	aggPaginatedData, err := New(collection).SetCollation(&collation).Context(ctx).Limit(limit).Page(page).Sort("price", -1).Aggregate(match, projectQuery)
	if err != nil {
		panic(err)
	}

	var aggProductList []Product
	for _, raw := range aggPaginatedData.Data {
		var product *Product
		if marshallErr := bson.Unmarshal(raw, &product); marshallErr == nil {
			aggProductList = append(aggProductList, *product)
		}

	}

	// print ProductList
	fmt.Printf("Aggregate Product List: %+v\n", aggProductList)

	// print pagination data
	fmt.Printf("Aggregate Pagination Data: %+v\n", aggPaginatedData.Data)
}

For Normal queries

func main() {
	// Establishing mongo db connection
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}

	// Example for Normal Find query
    	filter := bson.M{}
    	var limit int64 = 10
    	var page int64 = 1
    	collection := client.Database("myaggregate").Collection("stocks")
    	projection := bson.D{
    		{"name", 1},
    		{"qty", 1},
    	}
    	// Querying paginated data
    	// Sort and select are optional
        // Multiple Sort chaining is also allowed
        // If you want to do some complex sort like sort by score(weight) for full text search fields you can do it easily
        // sortValue := bson.M{
        //		"$meta" : "textScore",
        //	}
        // aggPaginatedData, err := paginate.New(collection).Context(ctx).Limit(limit).Page(page).Sort("score", sortValue)...
        var products []Product
    	paginatedData, err := New(collection).Context(ctx).Limit(limit).Page(page).Sort("price", -1).Select(projection).Filter(filter).Decode(&products).Find()
    	if err != nil {
    		panic(err)
    	}
    
    	// paginated data or paginatedData.Data will be nil because data is already decoded on through Decode function
    	// pagination info can be accessed in  paginatedData.Pagination
    	// print ProductList
    	fmt.Printf("Normal Find Data: %+v\n", products)
    
    	// print pagination data
    	fmt.Printf("Normal find pagination info: %+v\n", paginatedData.Pagination)
}
    

Notice:

paginatedData.data //it will be nil incase of  normal queries because data is already decoded on through Decode function

Running the tests

$ go test

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Acknowledgments

  1. https://github.com/mongodb/mongo-go-driver

MIT License

Copyright (c) 2021

More Repositories

1

truthy

Open source headless CMS API written using NestJS, that has pre built modules like User Management, Role Management, Permission Management, Email Module, Account Settings, OTP, Throttling, RBAC support, Localization, and many more.
TypeScript
486
star
2

stringy

Convert string to camel case, snake case, kebab case / slugify, custom delimiter, pad string, tease string and many other functionalities with help of by Stringy package.
Go
226
star
3

truthy-react-frontend

Truthy CMS's Frontend application written in ReactJS & Redux Saga. This project includes UI implementation of User Management, Role Management, Permission Management, Email Module, Account Settings, OTP, RBAC support, Localization, and many more.
JavaScript
97
star
4

vending-machine-demo

Application made with Nodejs typescript framework Nestjs and Reactjs Redux Saga to simulate simple vending machine workflow.
JavaScript
17
star
5

custom-validator

This package was build to beautify the Gin Gonic Binding validation error message for API. You can register your custom validation and easily add customize its message as you like.
Go
14
star
6

golang-oauth

Build your own Golang custom Oauth server with mysql driver.
Go
14
star
7

go-cold

Go Cold is Browser Extension with which you can block any website by automatic detection or by manual process on timer basis or block it always.
JavaScript
10
star
8

vue-polygon-cropper

Vue polygon cropper lets you to crop image with any numbers of points with redo and undo functionality.
Vue
10
star
9

laravel-demo

This is demo repository for new Laravel developer which includes demo of Laravel CMS with frontend with Vuejs. This repository contains demo implementation of Laravel policies, real time notification with laravel-echo-json with some example of feature tests.
PHP
10
star
10

Node-workshop

Resource repo for 60 hours node-workshop held for IIMS Bsc.It 6th & 9th sem
JavaScript
9
star
11

gobeam

Gobeam Profile
7
star
12

Golang_workshop

workshop on golang
Go
7
star
13

springMvcMusicShopCms

This is demo content management system made by using spring MVC.
JavaScript
7
star
14

node_app_demo_iims

Node app demo project
JavaScript
4
star
15

how_to_write_clean_code

Guide on how to write clean and organized code
3
star
16

promise_workshop

JavaScript
1
star
17

truthy-contributors

1
star
18

training_session

This is example repo to push code to remote repository
JavaScript
1
star