Code
Code

Reputation: 11

How to get all element from mongoDB array using go?

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?

Upvotes: 1

Views: 2646

Answers (2)

Mafya Original
Mafya Original

Reputation: 1


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"

                }
            ]
    }
]

Upvotes: 0

divan
divan

Reputation: 2817

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))
}

Upvotes: 4

Related Questions