Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mgm

> 数据库
Open source

Mongo Go Models (mgm) is a fast and simple MongoDB ODM for Go (based on official Mongo Go Driver)

763 stars0 likes1 views
WebsiteGitHub

About

Mongo Go Models (mgm) is a fast and simple MongoDB ODM for Go (based on official Mongo Go Driver)

Mongo Go Models

The Mongo ODM for Go

  • Features
  • Requirements
  • Installation
  • Usage
  • Bugs / Feature Requests
  • Communicate With Us
  • Contributing
  • License

Features

  • Define your models and perform CRUD operations with hooks before/after each operation.
  • mgm makes Mongo search and aggregation super easy to do in Golang.
  • Just set up your configs once and get collections anywhere you need them.
  • mgm predefines all Mongo operators and keys, so you don't have to hardcode them yourself.
  • mgm wraps the official Mongo Go Driver.

Requirements

  • Go 1.22 or higher.
  • MongoDB 4.0 and higher (required by the official driver v2).

Upgrading to the mongo-driver v2 based release

mgm now wraps go.mongodb.org/mongo-driver/v2. If you're upgrading from a release based on driver v1, note these breaking changes:

  • Import go.mongodb.org/mongo-driver/v2/... instead of go.mongodb.org/mongo-driver/....
  • primitive.ObjectID is now bson.ObjectID (the bson/primitive package was removed in v2).
  • TransactionFunc receives (session *mongo.Session, sc context.Context) instead of (session mongo.Session, sc mongo.SessionContext).
  • Collection and operation options use the driver's builder API (e.g. options.FindOne().SetComment(...)); bare option struct pointers are no longer accepted.

Installation

bash
go get github.com/kamva/mgm/v3

Usage

To get started, import the mgm package and setup the default config:

go
import (
   "github.com/kamva/mgm/v3"
   "go.mongodb.org/mongo-driver/v2/mongo/options"
)

func init() {
   // Setup the mgm default config
   err := mgm.SetDefaultConfig(nil, "mgm_lab", options.Client().ApplyURI("mongodb://root:12345@localhost:27017"))
}

Define your model:

go
type Book struct {
   // DefaultModel adds _id, created_at and updated_at fields to the Model.
   mgm.DefaultModel `bson:",inline"`
   Name             string `json:"name" bson:"name"`
   Pages            int    `json:"pages" bson:"pages"`
}

func NewBook(name string, pages int) *Book {
   return &Book{
      Name:  name,
      Pages: pages,
   }
}

Insert new document:

go
book := NewBook("Pride and Prejudice", 345)

// Make sure to pass the model by reference (to update the model's "updated_at", "created_at" and "id" fields by mgm).
err := mgm.Coll(book).Create(book)

Find one document

go
// Get the document's collection
book := &Book{}
coll := mgm.Coll(book)

// Find and decode the doc to a book model.
_ = coll.FindByID("5e0518aa8f1a52b0b9410ee3", book)

// Get the first doc of the collection 
_ = coll.First(bson.M{}, book)

// Get the first doc of a collection using a filter
_ = coll.First(bson.M{"pages":400}, book)

Update a document

go
// Find your book
book := findMyFavoriteBook()

// and update it
book.Name = "Moulin Rouge!"
err := mgm.Coll(book).Update(book)

Delete a document

go
// Just find and delete your document
err := mgm.Coll(book).Delete(book)

Find and decode a result:

go
result := []Book{}

err := mgm.Coll(&Book{}).SimpleFind(&result, bson.M{"pages": bson.M{operator.Gt: 24}})

A Model's Default Fields

Each model by default (by using DefaultModel struct) has the following fields:

  • _id : The document ID.

  • created_at: The creation date of a doc. When saving a new doc, this is automatically populated by the Creating hook.

  • updated_at: The last updated date of a doc. When saving a doc, this is automatically populated by the Saving hook.

You can even implement your own default model to customize its fields.

A Model's Hooks

Each model has the following hooks:

  • Creating: Called when creating a new model. Signature : Creating(context.Context) error

  • Created: Called after a new model is created. Signature : Created(context.Context) error

  • Updating: Called when updating model. Signature : Updating(context.Context) error

  • Updated : Called after a model is updated. Signature : Updated(ctx context.Context, result *mongo.UpdateResult) error

  • Saving: Called when creating or updating a model. Signature : Saving(context.Context) error

  • Saved: Called after a model is created or updated. Signature: Saved(context.Context) error

  • Deleting: Called when deleting a model. Signature: Deleting(context.Context) error

  • Deleted: Called after a model is deleted. Signature: Deleted(ctx context.Context, result *mongo.DeleteResult) error

Notes about hooks:

  • Each model by default uses the Creating and Saving hooks, so if you want to define those hooks yourself, remember to invoke the DefaultModel hooks from your own hooks.
  • Collection methods that call these hooks:
    • Create & CreateWithCtx
    • Update & UpdateWithCtx
    • Delete & DeleteWithCtx

Example:

go
func (model *Book) Creating(ctx context.Context) error {
   // Call the DefaultModel Creating hook
   if err := model.DefaultModel.Creating(ctx); err!=nil {
      return err
   }

   // We can validate the fields of a model and return an error to prevent a document's insertion.
   if model.Pages /mgm && cd mgm`)
1. Create your feature branch (`git checkout -b my-new-feature`)
1. Make changes and add them (`git add .`)
1. Commit your changes (`git commit -m 'Add some feature'`)
1. Push to the branch (`git push origin my-new-feature`)
1. Create new pull request

## License

Mongo Go Models is released under the [Apache License](https://github.com/Kamva/mgm/blob/master/LICENSE)

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gogomgmmodelmongo

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库