builder

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2021 License: GPL-3.0 Imports: 4 Imported by: 0

README

Filter Builder For Mongo Go Driver

Installation

go get github.com/tarupo/mongo-filter-builder

Usage

Here shows a simple usage for query a struct with specific filed and value. More usages can be found in test files.

import (
	builder "github.com/tarupo/mongo-filter-builder"
)

// Suppose we have a struct looks like this.
// And we would like to find its data from the mongodb.
type CustomStruct struct {
  Name string `bson:"name"`
  CapName int `bson:"capName"`
}

func main() {
  // To build a simple filter
  filter := builder.New().WantStr("name").Eq("volinda").Build()
  
  ...
  // use the filter in mongo-go-driver's method
  coll.FindOne(ctx, filter)
  
  
  // condtions are in AND mode as default, you can use Or() to compose more condtions.
  andFilter := builder.New().
  WantStr("name").Eq("volinda").
  WantStr("capName").Eq("VOLINDA").Build()
  
  
  // the same as in bson:
  // $or: [
  //   {name: "volinda", capName: "VOLINDA"},
  //   {name: "phile"}
  // ]
  orFilter := builder.New().
  WantStr("name").Eq("volinda").
  WantStr("capName").Eq("VOLINDA").
  Or().
  WantStr("name").Eq("phile").Build()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder represents a filter builder.

func New

func New() *Builder

New constructs a new Builder.

func (*Builder) Build

func (b *Builder) Build() bson.M

Build builds final filter and returns it. Build usually should be only called once since it will call b.Flush() after build up the final map.

func (*Builder) Date

func (b *Builder) Date(key string, defaultFormat ...string) *dateCond

func (*Builder) Flush

func (b *Builder) Flush() *Builder

Flush restes the builder to initial state

func (*Builder) Num

func (b *Builder) Num(key string) *numCond

Num indicates the builder to build a condtion for number type.

func (*Builder) Or

func (b *Builder) Or() *Builder

Or appends b.curMap to b.condMaps, and b.curMap will be assigned to a new empty map. Thus if finally b.condMaps's len is bigger than 1, then the final filter will wraps all maps into a $or condtion.

func (*Builder) Str

func (b *Builder) Str(key string) *strCond

WantNum indicates the builder to build a condtion for string type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL