Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetching the data from a mongodb in golang

Tags:

mongodb

go

I'm trying to fetch data from mongodb in golang using the gopkg.in/mgo.v2 driver, the format of the data is not fixed , as in few rows will be containing some fields which other rows might not.

here is the code for the same

session, err := mgo.Dial("mongodb://root:root@localhost:27017/admin")
db := session.DB("test")
fmt.Println(reflect.TypeOf(db))
CheckError(err,"errpor")
result := make(map[string]string)
//query := make(map[string]string)
//query["_id"] = "3434"

err1 := db.C("mycollection").Find(nil).One(&result)
CheckError(err1,"error")
for k := range result {
    fmt.Println(k)
}

Now the data contained in the collection is { "_id" : "3434", "0" : 1 }, however the for loop gives the output as _id , shouldn't there be two keys '_id' and '0' ? or am I doing something wrong here.

like image 312
Kanwal Prakash Singh Avatar asked Dec 07 '25 05:12

Kanwal Prakash Singh


1 Answers

oh I found the solution the "result" variable should be of type bson.M and then you can typecast accordingly as you go deep into the nesting structure.

like image 89
Kanwal Prakash Singh Avatar answered Dec 08 '25 18:12

Kanwal Prakash Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!