How to retrieve value from map - go lang?

半世苍凉 提交于 2019-12-22 11:19:55

问题


I am working with mgo to use MongoDB with Go. I have the following code:

func Find(collectionName, dbName string, query interface{}) (result []interface{}, err error) {
    collection := session.DB(dbName).C(collectionName)
    err = collection.Find(query).All(&result)
    return result, err
}

func GetTransactionID() (id interface{}, err error) {
    query := bson.M{}
    transId, err := Find("transactionId", dbName, query)
    for key, value := range transId {
        fmt.Println("k:", key, "v:", value)
    }
}

Output: k: 0 v: map[_id:ObjectIdHex("536887c199b6d0510964c35b") transId:A000000000]

I need to get the values of _id and transId from the map value returned in the slice from Find. How can I do that?


回答1:


I'm just guessing but in case you just want to retrieve all Transaction documents and print them - here is how:

Given you have a struct representing the structure of the documents of your collection e.g.:

type Transaction struct {
  Id            bson.ObjectId `bson:"_id"`
  TransactionId string        `bson:"transId"`
}

You can obtain all the documents using the MongoDB driver (mgo):

var transactions []Transaction
err = c.Find(bson.M{}).All(&transactions)
// handle err
for index, transaction := range transactions {
  fmt.Printf("%d: %+v\n", index, transaction)
}

Addition (generic solution)

OK, after you provided some more insight this might be a generic solution without using a struct. Try to marshall into a BSON document bson.M (not tested):

var data []bson.M
err := c.Find(bson.M{}).All(&data)
// handle err 
for _, doc := range data {
  for key, value := range doc {
    fmt.Println(key, value)
  }
}    


来源:https://stackoverflow.com/questions/23488704/how-to-retrieve-value-from-map-go-lang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!