Files
goext/mongoext/projections.go
T
viktor 852468f976 updated mongo driver dependencies to v2
# Conflicts:
#	exerr/constructor.go
#	exerr/dataCategory.go
#	exerr/dataSeverity.go
#	exerr/dataType.go
#	exerr/exerr.go
#	go.mod
#	mongoext/registry.go
#	reflectext/primStrSer.go
#	rfctime/date.go
#	rfctime/rfc3339.go
#	rfctime/rfc3339Nano.go
#	rfctime/seconds.go
#	rfctime/unix.go
#	rfctime/unixMilli.go
#	rfctime/unixNano.go
#	wmo/collection.go
#	wmo/queryInsert.go
2026-04-21 17:07:02 +02:00

31 lines
692 B
Go

package mongoext
import (
"go.mongodb.org/mongo-driver/v2/bson"
"reflect"
"strings"
)
// ProjectionFromStruct automatically generated a mongodb projection for a struct
// This way you can pretty much always write
// `options.FindOne().SetProjection(mongoutils.ProjectionFromStruct(...your_model...))`
// to only get the data from mongodb that you will actually use in the later decode step
func ProjectionFromStruct(obj interface{}) bson.M {
v := reflect.ValueOf(obj)
t := v.Type()
result := bson.M{}
for i := 0; i < v.NumField(); i++ {
tag := t.Field(i).Tag.Get("bson")
if tag == "" {
continue
}
tag = strings.Split(tag, ",")[0]
result[tag] = 1
}
return result
}