如何使用mgo从mongodb获取的切片中设置所有数据?

I am trying to fetch data from MongoDB that has dynamic keys and set it in a slice.

Here is my data sample:

_id ObjectIdHex("5911786dc28f25578150501d")
2017-05-01 [800 1000 1200 1400 1600]
_id ObjectIdHex("59117897c28f25578150501e")
2017-05-02 [800 1000 1200 1400 1600]
_id ObjectIdHex("5911789ec28f25578150501f")
2017-05-03 [800 1000 1200 1400 1600]
2017-05-04 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178a6c28f255781505020")
_id ObjectIdHex("591178abc28f255781505021")
2017-05-05 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178b0c28f255781505022")
2017-05-06 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178b5c28f255781505023")
2017-05-07 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178bac28f255781505024")
2017-05-08 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178c8c28f255781505025")
2017-05-09 [800 1000 1200 1400 1600]
2017-05-10 [800 1000 1200 1400 1600]

I need to set it into an array like {2017-05-09 : [800 1000 1200 1400 1600]} and same for other entries.

I have tried

package main

import(
    "fmt"
    "gopkg.in/mgo.v2/bson"
    //"encoding/json"
)

type Spot struct{
    Id      bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Spots   map[string]interface{} `json:"spots"`
}

//type Values []Value

//var result []struct{ Value int }
type Spots []Spot

func getAllSpots() (Spots) {
    mongoSession := getDbSession()

    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()
    var spots []Spot
    c := mongoSession.DB("test").C("spots")
    var data []bson.M
    err := c.Find(bson.M{}).All(&data)
    if err != nil {
        panic(err)
        // TODO: Do something about the error
    }

    test := make(map[string]int)
    for _, doc := range data {
      for key, value := range doc {
        if(key == "_id"){
            test[key] = value
            fmt.Println(key, value)
        }
      }
    }    

    return spots
}

I am able to get the spots in data and able to write the output to the console using fmt.Println() but when I assign it to a slice it gives me the following error:

cannot use value (type interface {}) as type int in assignment: need type assertion

I searched all over the web but couldn't find a valid solution. Can anyone please guide me what am I doing wrong?

查看全部
doutizhou5312
doutizhou5312
2017/05/11 12:26
  • mongodb
  • 点赞
  • 收藏
  • 回答
    私信

1个回复