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: over 1 year 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 (about 6 years ago)
- Default Branch: master
- Last Pushed: 2022-11-14T04:04:25.000Z (over 3 years ago)
- Last Synced: 2025-02-27T05:56:09.108Z (over 1 year ago)
- Topics: bson, go, golang, mongo
- Language: Go
- Homepage: https://pkg.go.dev/github.com/chidiwilliams/flatbson
- Size: 33.2 KB
- Stars: 67
- Watchers: 3
- Forks: 9
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# FlatBSON
[](https://github.com/chidiwilliams/flatbson/actions?query=workflow%3ABuild) [](https://pkg.go.dev/github.com/chidiwilliams/flatbson?tab=doc) [](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
```