dongwenxiu5200 2014-05-06 07:38
浏览 19
已采纳

如何从地图中获取价值-Go语言?

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条回答 默认 最新

  • duannaxin9975 2014-05-06 09:26
    关注

    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
    ", 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)
      }
    }    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大