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

我对mongodb和golang非常陌生。 我里面有一个名为“ myplace”的集合,一个名为region的字段是一个值数组,我们可以通过它检索整个数组。</ p>

我的集合看起来像</ p>

  {
“ _id”:ObjectId(“ 5474227309d76eb732acd134”),
“城市”:“某座城市”,
“区域”:[
{
“ regionid”:“ 31“,
” historical_place“:”寺庙“

},
{
” regionid“:” 32“,
” historical_place“:”寺庙“
},
{
” regionid“:” 33“,
” historical_place“:”寺庙“

}
]
}
</ code> </ pre>

期望输出</ p>

  [
{
“ City”:“ Some CIty”,
“ region”:[
{
“ regionid”:“ 31”,
“ historical_place” :“寺庙”

},
{
“ regionid”:“ 32”,
“ historical_place”:“寺庙”
},
{
“ regionid”:“ 33”,\ n“ historical_place”:“寺庙”

}
]
}
]
</ code> </ pre>

有什么解决方案?</ p>
</ DIV>

展开原文

原文

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个回答

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))
}
douliang4858
douliang4858 好答案。 另外,请查看mervine.net/json2struct以获得转换帮助。
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐