Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lyearn/mgod
MongoDB ODM for Go - Designed to work efficiently with Go models and official Mongo Go driver
https://github.com/lyearn/mgod
go models mongo mongo-go-models mongodb mongodb-go-odm mongodb-odm odm
Last synced: 24 days ago
JSON representation
MongoDB ODM for Go - Designed to work efficiently with Go models and official Mongo Go driver
- Host: GitHub
- URL: https://github.com/lyearn/mgod
- Owner: Lyearn
- License: mit
- Created: 2023-11-23T05:35:22.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-01-10T07:12:21.000Z (10 months ago)
- Last Synced: 2024-09-16T09:24:57.308Z (2 months ago)
- Topics: go, models, mongo, mongo-go-models, mongodb, mongodb-go-odm, mongodb-odm, odm
- Language: Go
- Homepage: https://lyearn.github.io/mgod/
- Size: 712 KB
- Stars: 35
- Watchers: 4
- Forks: 2
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
![logo](./images/logo.png)
# mgod
`mgod` is a MongoDB ODM specifically designed for Go. It provides a structured way to map Go models to MongoDB collections, simplifying database interactions in Go applications.
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Motivation](#motivation)
- [Future Scope](#future-scope)
- [Documentation](#documentation)
- [Contribute](#contribute)
- [License](#license)## Features
- **Reuse existing Go structs** to define models and perform Mongo operations.
- Automatic **field transformation** between Go and MongoDB using struct tags.
- Easily manage **meta fields** in models without cluttering Go structs.
- Supports **union types**, expanding data capabilities.
- Implement strict field requirements with struct tags for **data integrity**.
- Built-in support for **multi-tenant** systems.
- Wrapper around the **official** Mongo Go Driver.## Requirements
- Go 1.18 or higher.
- MongoDB 3.6 and higher.> [!WARNING]
> For MongoDB version **<4.4**, please create the collection in MongoDB before creating an `EntityMongoModel` using `mgod` for the same.
> Refer to [this MongoDB limitations](https://www.mongodb.com/docs/manual/reference/limits/#operations) for more information.## Installation
```
go get github.com/Lyearn/mgod
```## Basic Usage
Use existing MongoDB connection, or setup a new one to register a default database connection.For existing database connection,
```go
import "github.com/Lyearn/mgod"func init() {
// client is the MongoDB client obtained using Go Mongo Driver's Connect method.
mgod.SetDefaultClient(client)
}
```To setup a new connection,
```go
import (
"time""github.com/Lyearn/mgod"
"go.mongodb.org/mongo-driver/mongo/options"
)func init() {
// `cfg` is optional. Can rely on default configurations by providing `nil` value in argument.
cfg := &mgod.ConnectionConfig{Timeout: 5 * time.Second}
opts := options.Client().ApplyURI("mongodb://root:mgod123@localhost:27017")err := mgod.ConfigureDefaultClient(cfg, opts)
}
```Add tags _(wherever applicable)_ in existing struct _(or define a new model)_.
```go
type User struct {
Name string
EmailID string `bson:"emailId"`
Age *int32 `bson:",omitempty"`
JoinedOn string `bson:"joinedOn" mgoType:"date"`
}
```Use `mgod` to get the entity ODM.
```go
import (
"github.com/Lyearn/mgod"
"github.com/Lyearn/mgod/schema/schemaopt"
)model := User{}
dbName := "mgoddb"
collection := "users"opts := mgod.NewEntityMongoModelOptions(dbName, collection, nil)
userModel, _ := mgod.NewEntityMongoModel(model, *opts)
```Use the entity ODM to perform CRUD operations with ease.
Insert a new document.
```go
joinedOn, _ := dateformatter.New(time.Now()).GetISOString()
userDoc := User{
Name: "Gopher",
EmailID: "[email protected]",
JoinedOn: joinedOn,
}
user, _ := userModel.InsertOne(context.TODO(), userDoc)
```**Output:**
```js
{
"_id": ObjectId("65697705d4cbed00e8aba717"),
"name": "Gopher",
"emailId": "[email protected]",
"joinedOn": ISODate("2023-12-01T11:32:19.290Z"),
"__v": 0
}
```
---Find documents using model properties.
```go
users, _ := userModel.Find(context.TODO(), bson.M{"name": userDoc.Name})
```**Output:**
```go
[]User{
User{
Name: "Gopher",
EmailID: "[email protected]",
JoinedOn: "2023-12-01T11:32:19.290Z",
}
}
```## Motivation
Creating `mgod` was driven by the need to **simplify MongoDB interactions** while keeping **one schema for all** in Go. Traditionally, working with MongoDB in Go involved either using separate structs for database and service logic or manually converting service structs to MongoDB documents, a process that was both time-consuming and error-prone. This lack of integration often led to redundant coding, especially when dealing with union types or adding meta fields for each MongoDB operation.Inspired by the easy interface of MongoDB handling using [Mongoose](https://github.com/Automattic/mongoose) and [Typegoose](https://github.com/typegoose/typegoose) libraries available in Node, `mgod` aims to streamline these processes. It offers a more integrated approach, reducing the need to duplicate code and enhancing type safety, making MongoDB operations more intuitive and efficient in Go.
## Future Scope
The current version of mgod is a stable release. However, there are plans to add a lot more features like -
- [x] Implement a setup step for storing a default Mongo connection, eliminating the need to pass it during EntityMongoModel creation.
- [x] Provide support for transactions following the integration of default Mongo connection logic.
- [ ] Enable functionality to opt out of the default conversion of date fields to ISOString format.
- [ ] Develop easy to use wrapper functions around MongoDB Aggregation operation.
- [ ] Introduce automatic MongoDB collection selection based on Go struct names as a default behavior.
- [ ] Add test cases to improve code coverage.If you have any interesting feature requests, feel free to open an issue on [GitHub issue tracker](https://github.com/Lyearn/mgod/issues). We will be more than happy to discuss that!
## Documentation
For user facing documentation, check out [docs](docs/README.md).## Contribute
For contribution guidelines, check out [CONTRIBUTING](CONTRIBUTING.md).## License
`mgod` is licensed under the [MIT License](LICENSE).