douyun1852 2015-12-02 00:11
浏览 27
已采纳

Golang mgo结果分成简单的切片

I'm fairly new to both Go and MongoDB. Trying to select a single field from the DB and save it in an int slice without any avail.

userIDs := []int64{}

coll.Find(bson.M{"isdeleted": false}).Select(bson.M{"userid": 1}).All(&userIDs)

The above prints out an empty slice. However, if I create a struct with a single ID field that is int64 with marshalling then it works fine.

All I am trying to do is work with a simple slice containing IDs that I need instead of a struct with a single field. All help is appreciated.

  • 写回答

1条回答 默认 最新

  • dongyou7739 2015-12-02 01:29
    关注

    Because mgo queries return documents, a few lines of code is required to accomplish the goal:

    var result []struct{ UserID int64 `bson:"userid"` }
    err := coll.Find(bson.M{"isdeleted": false}).Select(bson.M{"userid": 1}).All(&result)
    if err != nil {
        // handle error
    }
    userIDs := make([]int64, len(result))
    for i := range result {
        userIDs[i] = result.UserID
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解