8arcturus / flatbson

Recursively flatten a Go struct using its BSON tags

Home Page:https://pkg.go.dev/github.com/chidiwilliams/flatbson

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FlatBSON

Build status API reference codecov

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:

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 for more information. (Thanks to @chidiwilliams)

The complete documentation is available on Godoc.

How to Install

go get -v github.com/8arcturus/flatbson

About

Recursively flatten a Go struct using its BSON tags

https://pkg.go.dev/github.com/chidiwilliams/flatbson

License:MIT License


Languages

Language:Go 100.0%