diff --git a/mango.go b/mango.go index 4eba515..671f159 100644 --- a/mango.go +++ b/mango.go @@ -2,6 +2,7 @@ package mango import ( "context" + "errors" "reflect" "strings" @@ -146,3 +147,34 @@ func valueToBson(v reflect.Value) interface{} { } return bson.D{} } + +func InsertMany(values interface{}) (*mongo.InsertManyResult, error) { + array := reflectutils.DeepValue(reflect.ValueOf(values)) + if !isArray(array) || isEmptyArray(array) { + return nil, errors.New("invalid input. Must be non empty array or slice") + } + + document := getMongoDocument(array) + if document.Context == nil { + return nil, errors.New("connection not registered in mongo document context") + } + + collection := document.collection(values) + bsonArray := arrayToBsonA(array) + return collection.InsertMany(document.Context, bsonArray) + +} + +func isArray(v reflect.Value) bool { + return v.Kind() == reflect.Array || v.Kind() == reflect.Slice +} + +func isEmptyArray(v reflect.Value) bool { + return v.Len() == 0 +} + +func getMongoDocument(array reflect.Value) *Document { + firstItem := array.Index(0) + document := firstItem.FieldByName("Document") + return document.Addr().Interface().(*Document) +}