How to get all element from mongoDB array using go? -
i new mongodb , golang. have collection named "myplace" inside that, 1 field named region array of values how can retrieve whole array.
my collection likes
{ "_id" : objectid("5474227309d76eb732acd134"), "city" : "some city", "region" : [ { "regionid" : "31", "historical_place" : "temple" }, { "regionid" : "32", "historical_place" : "temple" }, { "regionid" : "33", "historical_place" : "temple" } ] }
expecting output
[ { "city": "some city", "region":[ { "regionid" : "31", "historical_place" : "temple" }, { "regionid" : "32", "historical_place" : "temple" }, { "regionid" : "33", "historical_place" : "temple" } ] } ]
any solution?
create structs bson tags , use mgo's find().all(). , if need json output, use encoding/json package , marshalindent() function:
package main import ( "encoding/json" "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "log" ) type city struct { id bson.objectid `bson:"_id,omitempty" json:"-"` name string `bson:"city"` region []place `bson:"region"` } type place struct { regionid string `bson:"regionid"` histplace string `bson:"historical_place"` } func main() { session, err := mgo.dial("127.0.0.1") if err != nil { panic(err) } defer session.close() c := session.db("db").c("myplaces") var cities []city err = c.find(nil).all(&cities) if err != nil { log.fatal(err) } out, err := json.marshalindent(cities, " ", " ") if err != nil { log.fatal(err) } fmt.println("result:", string(out)) }
Comments
Post a Comment