1

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?

2 Answers 2

4

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))
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Also, check out mervine.net/json2struct for conversion help.
0

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)


var (
    mongodbUrl = "mongodb://127.0.0.1:27017/"
)

type MyPlace struct {
    ID                  primitive.ObjectID      `json:"_id,omitempty" bson:"_id,omitempty"`
    City                string                  `json:"city,omitempty" bson:"city,omitempty"`
    Regions             []Region                `json:"regions,omitempty" bson:"regions,omitempty"`
}

type Region struct {
    RegonID             string                  `json:"regionid,omitempty" bson:"regionid,omitempty"`
    HistoricalPlace     string                  `json:"historical_place,omitempty" bson:"historical_place,omitempty"`
}


func main() {
    var MyPlaces []MyPlace
    clientOptions := options.Client().
        ApplyURI(mongodbUrl)
    ctx := context.Background()
    
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Panic(err)
    }

    collection := client.Database("databseName").Collection("myplaces")

    cursor, err := collection.Find(ctx, bson.M{})
    if err != nil {
        log.Panic(err)
    }

    err = cursor.All(ctx, &MyPlaces)
    if err != nil {
        log.Panic(err)
    }

    data, err := json.Marshal(MyPlaces)
    if err != nil {
        log.Panic(err)
    }
    fmt.Println(string(data))
}

Output:

[
    {
        "_id" : "5474227309d76eb732acd134",
        "City" : "some city",
        "region" : [ 
                {
                    "regionid" : "31",
                    "historical_place" : "temple"

                }, 
                {
                    "regionid" : "32",
                    "historical_place" : "temple"
                }, 
                {
                    "regionid" : "33",
                    "historical_place" : "temple"

                }
            ]
    },
    {
        "_id" : "5474227309d76eb732acd134",
        "City" : "some city",
        "region" : [ 
                {
                    "regionid" : "31",
                    "historical_place" : "temple"

                }, 
                {
                    "regionid" : "32",
                    "historical_place" : "temple"
                }, 
                {
                    "regionid" : "33",
                    "historical_place" : "temple"

                }
            ]
    }
]

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.