简体   繁体   English

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

[英]How to set all data in a slice, got from mongodb using mgo?

I am trying to fetch data from MongoDB that has dynamic keys and set it in a slice. 我试图从具有动态密钥的MongoDB中获取数据并将其设置在切片中。

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. 我需要将其设置为类似{2017-05-09 : [800 1000 1200 1400 1600]}的数组,其他条目也应相同。

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: 我能够获取数据中的斑点,并能够使用fmt.Println()将输出写入控制台,但是当我将其分配给切片时,会出现以下错误:

cannot use value (type interface {}) as type int in assignment: need type assertion 不能在赋值中将值(类型接口{}类型)用作类型int:需要类型声明

I searched all over the web but couldn't find a valid solution. 我在网上搜索了所有内容,但找不到有效的解决方案。 Can anyone please guide me what am I doing wrong? 谁能指导我我在做什么错?

If you look at the documentation for bson.M , you'll see that it's just an alias for map[string]interface{} . 如果查看bson.M的文档,您会发现它只是map[string]interface{}的别名。 That means when you range over it, your key is a string , and your value is an interface{} . 这意味着当您对其进行range时,您的键是一个string ,而您的值是一个interface{} Your target is a map[string]int . 您的目标是map[string]int So when you test[key] = value , you're trying to assign value (an interface{} ) to something expecting an int , which you can't do without an explicit cast (aka type assertion ). 因此,当您test[key] = value ,您试图将value (一个interface{} )分配给一个期望为int ,而如果没有显式强制转换(即类型断言 ),则无法做到这一点。 This is exactly what the error message says: cannot use value (type interface {}) as type int in assignment: need type assertion . 这正是错误消息所表明的: cannot use value (type interface {}) as type int in assignment: need type assertion You could instead do: 您可以改为:

test[key] = value.(int)

But as a putu noted, it looks like those values are actually arrays of int s, which doesn't fit the test type at all, as it is a map of strings to single int values. 但是正如putu所指出的,看起来这些值实际上是int的数组,根本不适合test类型,因为它是字符串到单个int值的映射。 So you'd need to either change the type of test to map[string][]int or pick a value from the source array to store in the map, eg 因此,您需要将test类型更改为map[string][]int或从源数组中选择一个值以存储在地图中,例如

test[key] = (value.([]int))[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM