I am very new to mongodb and golang. I have a collection named "myplace" inside that, one field named region which is an array of values how we can retrieve the whole array.
my collection look 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 with bson tags and use mgo's Find().All(). And if you need an JSON output, use encoding/json package and 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))
}