drbuowqe02101 2014-11-27 07:55
浏览 529

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

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?

  • 写回答

1条回答 默认 最新

  • duanhongyi2964 2014-11-27 08:54
    关注

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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况