/colt

A productive MongoDB ODM for Go. Based on the official MongoDB driver but elegant to use

Primary LanguageGoMIT LicenseMIT

Colt

The mongodb ODM for Go i've always wanted

Build & Tests CodeQL Go.Dev reference Go Report Card Coverage Status

Colt leverages Generics to provide type-safe methods and decoding of documents. It therefor requires Go 1.18+.

Installation

To install Colt, use go get:

go get github.com/jensteichert/colt

Quick Start

package main

import (
	"fmt"
	"github.com/jensteichert/colt"
	"go.mongodb.org/mongo-driver/bson"
)

type Database struct {
	Todos *colt.Collection[*Todo]
}

type Todo struct {
	colt.DocWithTimestamps `bson:",inline"`
	Title string `bson:"title" json:"title"`
}

func main() {
	db := colt.Database{}
	db.Connect("mongodb://...", "myDatabaseName")

	database := Database{
		Todos: colt.GetCollection[*Todo](&db, "todos"),
	}

	newTodo := Todo{Title: "Hello"}

	todo, _ := database.Todos.Insert(&newTodo) // Will return a Todo
	insertedTodo, _ := database.Todos.FindById(todo.ID)

	allTodos, _ := database.Todos.Find(bson.M{"title": "Hello"})
}

Features

Hooks

BeforeInsert Hook

Triggers before a document will be inserted

type Todo struct {
	colt.DocWithTimestamps `bson:",inline"`
}

func(t *Todo) BeforeInsert() error {
	t.DocWithTimestamps.BeforeInsert()

        // Do something with t here
	return nil
}

BeforeUpdate Hook

Triggers before a document will be updated

func(t *Todo) BeforeUpdate() error {
	t.DocWithTimestamps.BeforeUpdate()

        // Do something with t here
	return nil
}

ToDo

  • CRUD
  • Hooks
  • Pagination
  • Aggregations
  • Transactions