Last active
October 25, 2018 18:52
-
-
Save lucaswxp/238bc8732d8e0280c2256cf40a0a9723 to your computer and use it in GitHub Desktop.
mongodb golang insert unknown/unstructured json document into collection - This function takes a interface{} and returns a structured bson.Document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"github.com/mongodb/mongo-go-driver/bson" | |
) | |
func formatDocument(evdata interface{}) *bson.Document { | |
doc := bson.NewDocument() | |
for k, v := range evdata.(map[string]interface{}) { | |
switch t := v.(type) { | |
case map[string]interface{}: | |
doc.Append(bson.EC.SubDocument(k, formatDocument(t))) | |
case []interface{}: | |
arr := formatArray(v.([]interface{})) | |
doc.Append(bson.EC.ArrayFromElements(k, arr...)) | |
default: | |
doc.Append(bson.EC.Interface(k, t)) | |
} | |
} | |
return doc | |
} | |
func formatArray(v []interface{}) []*bson.Value { | |
arr := make([]*bson.Value, len(v)) | |
for k2, v2 := range v { | |
var val *bson.Value | |
switch v2.(type) { | |
case map[string]interface{}: | |
val = bson.VC.Document(formatDocument(v2)) | |
case []interface{}: | |
arr := v2.([]interface{}) | |
val = bson.VC.ArrayFromValues(formatArray(arr)...) | |
default: | |
val = bson.EC.Interface("", v2).Value() | |
} | |
arr[k2] = val | |
} | |
return arr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment