Files
goext/mongoext/projections.go
T
viktor 26d542c9a2
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m33s
added mongo-driver v2
2026-04-21 18:41:32 +02:00

32 lines
693 B
Go

package mongoext
import (
"reflect"
"strings"
"go.mongodb.org/mongo-driver/v2/bson"
)
// 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
}