Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/chidiwilliams/flatbson
Recursively flatten a Go struct using its BSON tags
https://github.com/chidiwilliams/flatbson
bson go golang mongo
Last synced: 24 days ago
JSON representation
Recursively flatten a Go struct using its BSON tags
- Host: GitHub
- URL: https://github.com/chidiwilliams/flatbson
- Owner: chidiwilliams
- License: mit
- Created: 2020-05-19T10:16:15.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-11-14T04:04:25.000Z (about 2 years ago)
- Last Synced: 2024-10-10T19:26:47.953Z (about 1 month ago)
- Topics: bson, go, golang, mongo
- Language: Go
- Homepage: https://pkg.go.dev/github.com/chidiwilliams/flatbson
- Size: 33.2 KB
- Stars: 65
- Watchers: 3
- Forks: 9
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# FlatBSON
[![Build status](https://github.com/chidiwilliams/flatbson/workflows/Build/badge.svg)](https://github.com/chidiwilliams/flatbson/actions?query=workflow%3ABuild) [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/chidiwilliams/flatbson?tab=doc) [![codecov](https://codecov.io/gh/chidiwilliams/flatbson/branch/master/graph/badge.svg)](https://codecov.io/gh/chidiwilliams/flatbson)
FlatBSON recursively flattens a Go struct using its BSON tags.
It is particularly useful for partially updating embedded Mongo documents.
For example, to update a `User`'s `Address.Visited` field, first call `flatbson.Flatten` with the parent struct:
```go
type User struct {
ID bson.ObjectID `bson:"_id,omitempty"`
Name string `bson:"name,omitempty"`
Address Address `bson:"address,omitempty"`
}type Address struct {
Street string `bson:"street,omitempty"`
City string `bson:"city,omitempty"`
State string `bson:"state,omitempty"`
VisitedAt time.Time `bson:"visitedAt,omitempty"`
}flatbson.Flatten(User{Address: {VisitedAt: time.Now().UTC()}})
// Result:
// map[string]interface{}{"address.visitedAt": time.Time{...}}
```Passing the result to `coll.UpdateOne` updates only the `address.VisitedAt` field instead of overwriting the entire `address` embedded document. See this [blog post](https://dev.to/chidiwilliams/partially-updating-an-embedded-mongo-document-in-go-knn) for more information.
The complete documentation is available on [Godoc](https://pkg.go.dev/github.com/chidiwilliams/flatbson).
## How to Install
```shell script
go get -v github.com/chidiwilliams/flatbson
```