简体   繁体   English

如何从地图中检索价值 - 去郎?

[英]How to retrieve value from map - go lang?

I am working with mgo to use MongoDB with Go. 我正在使用mgo将MongoDB与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] 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 . 我需要从Find的切片中返回的map值中获取_idtransId的值。 How can I do that? 我怎样才能做到这一点?

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 eg: 假设您有一个表示集合文档struct的结构,例如:

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

You can obtain all the documents using the MongoDB driver (mgo): 您可以使用MongoDB驱动程序(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): 尝试编组到BSON文档bson.M (未测试):

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)
  }
}    

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

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