@@ -2,11 +2,12 @@ package elemental
22
33import (
44 "context"
5- "github.com/elcengine/elemental/utils"
6- "github.com/spf13/cast"
75 "reflect"
86 "strings"
97
8+ "github.com/elcengine/elemental/utils"
9+ "github.com/spf13/cast"
10+
1011 "github.com/gertd/go-pluralize"
1112 "github.com/samber/lo"
1213 "go.mongodb.org/mongo-driver/bson"
@@ -234,30 +235,27 @@ func (m Model[T]) Sort(args ...any) Model[T] {
234235// Extends the query with a projection stage.
235236// The projection stage is used to specify which fields to include or exclude from the results.
236237func (m Model [T ]) Select (fields ... any ) Model [T ] {
238+ inputType := reflect .TypeOf (fields [0 ]).Kind ()
239+ if inputType == reflect .Map {
240+ m .pipeline = append (m .pipeline , bson.D {{Key : "$project" , Value : fields [0 ]}})
241+ return m
242+ }
237243 var selection []string
238244 switch {
239- case len (fields ) == 1 && reflect .TypeOf (fields [0 ]).Kind () == reflect .String :
245+ case inputType == reflect .Slice :
246+ selection = fields [0 ].([]string )
247+ case len (fields ) == 1 && inputType == reflect .String :
240248 selection = strings .FieldsFunc (fields [0 ].(string ), func (r rune ) bool {
241249 return r == ',' || r == ' '
242250 })
243251 case len (fields ) > 1 :
244- selection = utils.CastSlice [string ](fields )
245- case reflect .TypeOf (fields [0 ]).Kind () == reflect .Slice :
246- selection = fields [0 ].([]string )
252+ selection = cast .ToStringSlice (fields )
247253 }
248-
249- switch {
250- case len (selection ) > 0 :
251- for _ , field := range selection {
252- if strings .HasPrefix (field , "-" ) {
253- m = m .addToPipeline ("$project" , field [1 :], 0 )
254- } else {
255- m = m .addToPipeline ("$project" , field , 1 )
256- }
257- }
258- case reflect .TypeOf (fields [0 ]).Kind () == reflect .Map :
259- for field , value := range utils.Cast [primitive.M ](fields [0 ]) {
260- m = m .addToPipeline ("$project" , field , value )
254+ for _ , field := range selection {
255+ if strings .HasPrefix (field , "-" ) {
256+ m = m .addToPipeline ("$project" , field [1 :], 0 )
257+ } else {
258+ m = m .addToPipeline ("$project" , field , 1 )
261259 }
262260 }
263261 return m
@@ -286,8 +284,3 @@ func (m Model[T]) Clone() Model[T] {
286284 deletedAtFieldName : m .deletedAtFieldName ,
287285 }
288286}
289-
290- // This feature is still experimental and not fully implemented.
291- func (m Model [T ]) UseCluster (connection * string ) ClusterOp [T ] {
292- return Cluster (& m , connection )
293- }
0 commit comments