simplequery

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2020 License: MIT Imports: 8 Imported by: 0

README

go-simplequery-mongodb

Convert a condition query to MongoDB query syntax

Example

filter, _ := Parse(`foo < 5 AND (bar >= 10 OR baz = "example" OR qux = /[a-z]{3,5}/i)`)

generates a nested bson.M struct with the following nested structure:

{"$and":[{"foo":{"$lt":5}},{"$or":[{"$or":[{"bar":{"$gte":10}},{"baz":{"$eq":"example"}}]},{"qux":{"$eq":{"Key":"$regex","Value":{"Pattern":"[a-z]{3,5}","Options":"i"}}}}]}]}

that can be used in MongoDB's .Find(), .Aggregate(), Count(), ... functions.

Supported are the following operators:

Operator Syntax
Parentheses (<exp>)
Logical AND <exp1> AND <exp2>
Logical OR <exp1> OR <exp2>
Logical NOT NOT <exp>
LT <field> < <value>
LTE <field> <= <value>
GT <field> > <value>
GTE <field> >= <value>
EQ (INT) <field> = <int>
EQ (STR) <field> = "<str>"
EQ (RGX) <field> = /<rgx>/<opt>
NE (INT) <field> != <int>
NE (STR) <field> != "<str>"
NE (RGX) <field> != /<rgx>/<opt>

more operators like EXISTS or IN are coming soon ...

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(condition string) (bson.M, error)
Example
package main

import (
	"encoding/json"
	"fmt"
)

func parseAndPrint(cond string) {
	filter, err := Parse(cond)
	if err != nil {
		panic(err)
	}
	b, err := json.Marshal(filter)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}

func main() {
	parseAndPrint(`foo < 5 AND (bar >= 10 OR baz = "example" OR qux = /[a-z]{3,5}/i)`)
	parseAndPrint(`foo = "bar" AND NOT (baz = "")`)
}
Output:

{"$and":[{"foo":{"$lt":5}},{"$or":[{"$or":[{"bar":{"$gte":10}},{"baz":{"$eq":"example"}}]},{"qux":{"$eq":{"Key":"$regex","Value":{"Pattern":"[a-z]{3,5}","Options":"i"}}}}]}]}
{"$and":[{"foo":{"$eq":"bar"}},{"$nor":[{"baz":{"$eq":""}}]}]}

Types

This section is empty.

Jump to

Keyboard shortcuts

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