Mongo Golang Search provides a query language to a MongoDB database.
Explore the docs
Report Bug
·
Request Feature
Mongo Golang Search provides a simple query language to perform advanced searches for your collections in MongoDB.
You could also use Mongo Golang Search to searching, sorting, pagination and combining logical operators.
The recommended way to get started using the Mongo Golang Search is by using Go modules to install the dependency in your project. This can be done either by importing packages from github.com/ajclopez/mgs and having the build step install the dependency or by explicitly running
For version 2.x.x, you can import packages from:
go get github.com/ajclopez/mgs/v2For version 1.x.x, you can import packages from:
go get github.com/ajclopez/mgsTo get started with mgs version 2 or later, implement a TypeConverter by creating a struct with a Convert method. This allows you to define how to convert primitive values (like ObjectIDs, etc.) from strings.
type TypeConverter struct{}
func (c *TypeConverter) Convert(value string) (interface{}, error) {
if id, err := primitive.ObjectIDFromHex(value); err == nil {
return id, err
}
return nil, fmt.Errorf("no conversion matched")
}Then create an instance of QueryHandler:
queryHandler := mgs.NewQueryHandler(&TypeConverter{})Finally use a mgs.MongoGoSearch function:
queryHandler.MongoGoSearch(query string, opts *FindOptions)See migration guide for details on upgrading from version 1 to version 2.
type Primitives struct{}
func (primitives *Primitives) ObjectID(oidStr string) (interface{}, error) {
return ObjectID() // invoke ObjectID from MongoDB Driver
}Then create an instance of QueryHandler:
queryHandler := mgs.NewQueryHandler(&Primitives{})Finally use a mgs.MongoGoSearch function:
queryHandler.MongoGoSearch(query string, opts *FindOptions)query: query string part of the requested API URL.
opts: object for advanced configuration See below [optional].
Using mgs.MongoGoSearch function with mongo-go-driver library to filter, sort, limit and skip in MongoDB:
import (
"context"
"github.com/ajclopez/mgs"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Primitives struct{}
func (primitives *Primitives) ObjectID(oidStr string) (interface{}, error) {
return primitive.ObjectIDFromHex(oidStr)
}
queryHandler := mgs.NewQueryHandler(&Primitives{})
opts := mgs.FindOption()
result, err := queryHandler.MongoGoSearch(query, opts)
...
findOpts := options.Find()
findOpts.SetLimit(result.Limit)
findOpts.SetSkip(result.Skip)
findOpts.SetSort(result.Sort)
findOpts.SetProjection(result.Projection)
cur, err := collection.Find(context.TODO(), result.Filter, findOpts)
...Using optional configurations:
import (
"context"
"github.com/ajclopez/mgs"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Primitives struct{}
func (primitives *Primitives) ObjectID(oidStr string) (interface{}, error) {
return primitive.ObjectIDFromHex(oidStr)
}
queryHandler := mgs.NewQueryHandler(&Primitives{})
opts := mgs.FindOption()
opts.SetCaster(map[string]mgs.CastType{
"mobile": mgs.STRING,
})
opts.SetMaxLimit(1000)
opts.SetDefaultLimit(10)
result, err := queryHandler.MongoGoSearch(query, opts)
...
findOpts := options.Find()
findOpts.SetLimit(result.Limit)
findOpts.SetSkip(result.Skip)
findOpts.SetSort(result.Sort)
findOpts.SetProjection(result.Projection)
cur, err := collection.Find(context.TODO(), result.Filter, findOpts)
...A request of the form:
'employees?status=sent&date>2020-01-06T14:00:00.000Z&author.firstname=Jhon&skip=50&limit=100&sort=-date&fields=id,date';Is translated to:
Query{
Filter: map[string]interface{}{
"author.firstname": "John",
"date": map[string]interface{}{"$gt": "2020-01-06T14:00:00.000Z"},
"status": "SENT",
},
Sort: map[string]int{
"date": 1,
"id": 1
},
Limit: 100,
Skip: 50,
}| Operator | URI | Example |
|---|---|---|
$eq |
key=val |
type=public |
$ne |
key!=val |
status!=SENT |
$gt |
key>val |
price>5 |
$gte |
key>=val |
price>=9 |
$lt |
key<val |
date<2020-01-01T14:00:00.000Z |
$lte |
key<=val |
priority<=-5 |
$in |
key=val1,val2 |
status=QUEUED,DEQUEUED |
$nin |
key!=val1,val2 |
status!=QUEUED,DEQUEUED |
$exists |
key |
email |
$exists |
!key |
!email |
$regex |
key=/value/<opts> |
email=/@gmail\.com$/ |
$regex |
key!=/value/<opts> |
phone!=/^58/ |
Useful to limit the number of records returned.
- Operator keys are
skipandlimit. - Use
limitoperator to limit the number of records returned. - Use
skipoperator to skip the specified number of records.
skip=20&limit=10Useful to sort returned records.
- Operator key is
sort. - It accepts a comma-separated list of fields.
- Use
-prefixes to sort in descending order. - Use
+prefixes to sort in ascedending order.
sort=id,-dateUseful to limit fields to return in each records.
- Operator key is
fields. - It accepts a comma-separated list of fields.
fields=firstname,lastname,phone,emailNote:
- The
_idfield (returned by default).
For more advanced usage (and, or logic operations), pass query filter as string with the logical operations, for example:
filter=(country=Mexico OR country=Spain) and gender=female- Filtering operations.
- The
AND/andoperator. - The
OR/oroperator. - Parenthesis can be used for grouping.
You can use advanced options:
opts := mgs.FindOption()
opts.SetCaster(map[string]mgs.CastType{
"mobile": mgs.STRING,
})
opts.SetMaxLimit(100)
opts.SetDefaultLimit(10)FindOptioncreates a new FindOptions instance.SetCasterobject to specify custom casters, key is the caster name, and value is a type (BOOLEAN, NUMBER, PATTERN, DATE, STRING).SetDefaultLimitwhich contains custom value to return records.SetMaxLimitwhich contains custom value to return a maximum of records.
You can specify your own maximum or default limit value.
defaultLimit: custom value to return records.maxLimit: custom value to return a maximum of records.
opts := mgs.FindOption()
opts.SetMaxLimit(1000)
opts.SetDefaultLimit(10)
result, err := mgs.MongoGoSearch("city=Madrid&skip=10&limit=1000", opts)You can specify how query parameter values are casted by passing an object.
casters: object which map keys to casters.
opts := mgs.FindOption()
opts.SetCaster(map[string]mgs.CastType{
"key1": mgs.STRING,
"key2": mgs.NUMBER,
"key3": mgs.STRING,
"key4": mgs.BOOLEAN
})
result, err := mgs.MongoGoSearch("key1=VALUE&key2=10&key3=20&key4=true", opts)Please review the contributing guide.
This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code.
This software is released under the MIT license. See LICENSE for more information.