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 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?