如何使用go获取mongoDB数组中的所有元素?

时间:2014-11-27 07:55:46

标签: arrays mongodb go

我是mongodb和golang的新手。我有一个名为" myplace"在其中,一个名为region的字段是一个值数组,我们可以如何检索整个数组。

我的收藏品看起来像

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

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

    }
]
}

期待输出

 [
  {
    "City": "Some CIty",
    "region":[ 
     {
        "regionid" : "31",
        "historical_place" : "temple"

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

    }
   ]
  }
]

任何解决方案?

1 个答案:

答案 0 :(得分:4)

使用 bson 标签创建结构并使用mgo的Find()。All()。 如果您需要JSON输出,请使用 encoding / json 包和MarshalIndent()函数:

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