mongodb helper functions, document and pipeline builder

MongoUtils

Mongodb helper functions, document and pipeline builder.

Helpers

ParseObjectID

Parse object id from string.

ParseObjectID(id string) *primitive.ObjectID

IsValidObjectId

Check if object id is valid and not zero.

IsValidObjectId(id *primitive.ObjectID) bool

Doc Builder

Document builder is a helper type for creating mongo document (primitive.D) with chained methods.

import "github.com/bopher/mongoutils"
doc := mongoutils.NewDoc()
doc.
    Add("name", "John").
    Add("nick", "John2").
    Array("skills", "javascript", "go", "rust", "mongo")
fmt.Println(doc.Build())
// -> {
//   "name": "John",
//   "nick": "John2",
//   "skills": ["javascript","go","rust","mongo"]
// }

Doc Methods

Add

Add new element.

// Signature:
Add(k string, v interface{}) MongoDoc

// Example:
doc.Add("name", "Kim")

Doc

Add new element with nested doc value.

// Signature:
Doc(k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.Doc("age", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    d.Add("$gt", 20)
    d.Add("$lte", 30)
    return d
}) // -> { "age": { "$gt": 20, "$lte": 30 } }

Array

Add new element with array value.

// Signature:
Array(k string, v ...interface{}) MongoDoc

// Example:
doc.Array("skills", "javascript", "golang") // -> { "skills": ["javascript", "golang"] }

Nested

Add new nested element.

// Signature:
Nested(root string, k string, v interface{}) MongoDoc

// Example:
doc.Nested("$set", "name", "Jack") // { "$set": { "name": "Jack" } }

NestedDoc

Add new nested element with doc value.

// Signature:
NestedDoc(root string, k string, cb func(d MongoDoc) MongoDoc) MongoDoc

// Example:
doc.NestedDoc("$set", "address", func(d mongoutils.MongoDoc) mongoutils.MongoDoc {
    d.
        Add("city", "London").
        Add("street", "12th")
    return d
}) // -> { "$set": { "address": { "city": "London", "street": "12th" } } }

NestedArray

Add new nested element with array value.

// Signature:
NestedArray(root string, k string, v ...interface{}) MongoDoc

// Example:
doc.NestedArray("skill", "$in", "mongo", "golang") // -> { "skill": { "$in": ["mongo", "golang"] } }

Regex

Add new element with regex value.

// Signature:
Regex(k string, pattern string, opt string) MongoDoc

// Example:
doc.Regex("full_name", "John.*", "i") // -> { "full_name": { pattern: "John.*", options: "i" } }

Map

Creates a map from the elements of the Doc.

Map() primitive.M

Build

Generate mongo doc.

Build() primitive.D

Pipeline Builder

Pipeline builder is a helper type for creating mongo pipeline ([]primitive.D) with chained methods.

import "github.com/bopher/mongoutils"
pipe := mongoutils.NewPipe()
pipe.
    Add(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.Nested("$match", "name", "John")
        return d
    }).
    Group(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.
            Add("_id", "$_id").
            Nested("name", "$first", "$name")
            Nested("total", "$sum", "$invoice")
        return d
    })
fmt.Println(pipe.Build())
// -> [
//   { "$match": { "name": "John"} },
//   { "$group": {
//       "_id": "$_id"
//       "name": { "$first": "$name" },
//       "total": { "$sum": "$invoice" }
//   }}
// ]

Pipeline Methods

Add

Add new Doc.

// Signature:
Add(cb func(d MongoDoc) MongoDoc) MongoPipeline

// Example:
pipe.Add(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
    d.Nested("$match", "name", "John")
    return d
}) // -> [ {"$match": { "name": "John"}} ]

Lookup

Add $lookup stage.

// Signature:
Lookup(from string, local string, foreign string, as string) MongoPipeline

// Example:
pipe.Lookup("users", "user_id", "_id", "user")
// -> [
//     {"$lookup": {
//         "from": "users",
//         "localField": "user_id",
//         "foreignField": "_id",
//         "as": "user"
//     }}
// ]

Unwind

Add $unwind stage.

// Signature:
Unwind(path string, prevNullAndEmpty bool) MongoPipeline

// Example:
pipe.Unwind("services", true)
// -> [
//     {"$unwind": {
//         "path": "services",
//         "preserveNullAndEmptyArrays": true,
//     }}
// ]

Unwrap

Get first item of array and insert to doc using $addFields stage. When using lookup result returns as array, use this helper to unwrap lookup result as field.

// Signature:
Unwrap(field string, as string) MongoPipeline

// Example:
pipe.
    Lookup("users", "user_id", "_id", "__user").
    Unwrap("$__user", "user")
// -> [
//     { "$lookup": {
//         "from": "users",
//         "localField": "user_id",
//         "foreignField": "_id",
//         "as": "user"
//     }},
//     { "$addFields": { "user" : { "$first": "$__user" } } }
// ]

Group

Add $group stage.

// Signature:
Group(cb func(d MongoDoc) MongoDoc) MongoPipeline

// Example:
pipe.
    Group(func(d mongoutils.MongoDoc) mongoutils.MongoDoc{
        d.
            Add("_id", "$_id").
            Nested("name", "$first", "$name").
            Nested("total", "$sum", "$invoice")
        return d
    })
// -> [
//   { "$group": {
//       "_id": "$_id"
//       "name": { "$first": "$name" },
//       "total": { "$sum": "$invoice" }
//   }}
// ]

ReplaceRoot

Add $replaceRoot stage.

// Signature:
ReplaceRoot(v interface{}) MongoPipeline

// Example:
pipe.ReplaceRoot("$my_root")
// ->  [{ "$replaceRoot": {"newRoot": "$my_root" } }]

MergeRoot

Add $replaceRoot stage with $mergeObjects operator.

// Signature:
MergeRoot(fields ...interface{}) MongoPipeline

// Example:
pipe.MergeRoot("$my_root", "$$ROOT")
// -> [
//     {
//         "$replaceRoot": {
//             "newRoot": { "mergeObjects": ["$my_root", "$$ROOT"] }
//         }
//     }
// ]

UnProject

Generate $project stage to remove fields from result.

// Signature:
UnProject(fields ...string) MongoPipeline

// Example:
pipe.UnProject("my_root", "__user")
// -> [
//     { "$project": { "my_root": 0, "__user": 0 } }
// ]

Build

Generate mongo pipeline.

Build() mongo.Pipeline
Owner
Bardo Go Framework
Library based framework for golang
Bardo Go Framework
Similar Resources

Cloud-native and easy-to-use application management platform | 云原生且易用的应用管理平台

Cloud-native and easy-to-use application management platform | 云原生且易用的应用管理平台

Website • Documentation What is NEW! August 24, 2020 ,Rainbond 5.2 Stable version is officially released View Release Rainbond Introduction Cloud nati

Dec 29, 2022

Generates Golang client and server based on OpenAPI2 (swagger) definitions

Generates Golang client and server based on OpenAPI2 (swagger) definitions

ExperienceOne Golang APIKit ExperienceOne Golang APIKit Overview Requirements Installation Usage Generate standard project structure Define the API wi

Aug 9, 2022

Template repository for a Go monorepo, complete with CI and automatic docker builds

Utility Warehouse template Go monorepo This repo is an abbreviated copy of one used by one of the teams inside Utility Warehouse. It's been built for

Dec 19, 2022

Concourse is a container-based continuous thing-doer written in Go and Elm.

Concourse is a container-based continuous thing-doer written in Go and Elm.

Concourse: the continuous thing-doer. Concourse is an automation system written in Go. It is most commonly used for CI/CD, and is built to scale to an

Dec 30, 2022

Sample cloud-native application with 10 microservices showcasing Kubernetes, Istio, gRPC and OpenCensus.

Sample cloud-native application with 10 microservices showcasing Kubernetes, Istio, gRPC and OpenCensus.

Online Boutique is a cloud-native microservices demo application. Online Boutique consists of a 10-tier microservices application. The application is

Dec 31, 2022

Automatic Service Mesh and RPC generation for Go micro services, it's a humble alternative to gRPC with Istio.

Automatic Service Mesh and RPC generation for Go micro services, it's a humble alternative to gRPC with Istio.

Mesh RPC MeshRPC provides automatic Service Mesh and RPC generation for Go micro services, it's a humble alternative to gRPC with Istio. In a nutshell

Aug 22, 2022

Go microservice tutorial project using Domain Driven Design and Hexagonal Architecture!

"ToDo API" Microservice Example Introduction Welcome! 👋 This is an educational repository that includes a microservice written in Go. It is used as t

Jan 4, 2023

CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API server of Clean Architecture with Go(Echo), Gorm, MySQL, Docker and Swagger

CRUD API Server of Clean Architecture Go(echo) gorm mysql docker swagger build docker-compose up -d --build API Postman and Fiddler is recommended to

May 30, 2021

Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading.

Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading.

#1 Golang live reload and task runner Content - ⭐️ Top Features - 💃🏻 Get started - 📄 Config sample - 📚 Commands List - 🛠 Support and Suggestions

Dec 31, 2022
A Go library for building mongo queries with factory functions

FET Build query dynamically A Go library for building mongo queries with factory functions. What is FET? you can build queries with factory functions.

Sep 25, 2022
A microservice gateway developed based on golang.With a variety of plug-ins which can be expanded by itself, plug and play. what's more,it can quickly help enterprises manage API services and improve the stability and security of API services.
A microservice gateway developed based on golang.With a variety of plug-ins which can be expanded by itself, plug and play. what's more,it can quickly help enterprises manage API services and improve the stability and security of API services.

Goku API gateway is a microservice gateway developed based on golang. It can achieve the purposes of high-performance HTTP API forwarding, multi tenant management, API access control, etc. it has a powerful custom plug-in system, which can be expanded by itself, and can quickly help enterprises manage API services and improve the stability and security of API services.

Dec 29, 2022
Microservice Boilerplate for Golang with gRPC and RESTful API. Multiple database and client supported
Microservice Boilerplate for Golang with gRPC and RESTful API. Multiple database and client supported

Go Microservice Starter A boilerplate for flexible Go microservice. Table of contents Features Installation Todo List Folder Structures Features: Mult

Jul 28, 2022
Fast, intuitive, and powerful configuration-driven engine for faster and easier REST development
Fast, intuitive, and powerful configuration-driven engine for faster and easier REST development

aicra is a lightweight and idiomatic configuration-driven engine for building REST services. It's especially good at helping you write large APIs that remain maintainable as your project grows.

Oct 19, 2022
An example microservice demo using kubernetes concepts like deployment, services, persistent volume and claims, secrets and helm chart

Docker vs Kubernetes Docker Kubernetes container tech, isolated env for apps infra management, multiple containers automated builds and deploy apps -

Dec 13, 2021
Rpcx-framework - An RPC microservices framework based on rpcx, simple and easy to use, ultra fast and efficient, powerful, service discovery, service governance, service layering, version control, routing label registration.

RPCX Framework An RPC microservices framework based on rpcx. Features: simple and easy to use, ultra fast and efficient, powerful, service discovery,

Jan 5, 2022
GSOC-Mentorship - Scripts and Templates used to parse jsons and send mails to students of GSOC Mentorship

GSOC Mentorship The Club of Programmers, IIT(BHU) organizes it's flagship GSoC M

Sep 18, 2022
Connect, secure, control, and observe services.

Istio An open platform to connect, manage, and secure microservices. For in-depth information about how to use Istio, visit istio.io To ask questions

Jan 9, 2023
Design-based APIs and microservices in Go
Design-based APIs and microservices in Go

Goa is a framework for building micro-services and APIs in Go using a unique design-first approach. Overview Goa takes a different approach to buildin

Jan 5, 2023
Netflix's Hystrix latency and fault tolerance library, for Go

hystrix-go Hystrix is a great project from Netflix. Hystrix is a latency and fault tolerance library designed to isolate points of access to remote sy

Dec 28, 2022