将Golang mgo的结果转换为简单的切片

huangapple go评论74阅读模式
英文:

Golang mgo result into simple slice

问题

我对Go和MongoDB都比较新手。我试图从数据库中选择一个字段,并将其保存在一个int切片中,但没有成功。

userIDs := []int64{}

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

上述代码打印出一个空切片。然而,如果我创建一个具有单个ID字段的结构体,并进行编组,那么它就可以正常工作。

我只是想使用一个包含所需ID的简单切片,而不是一个只有一个字段的结构体。非常感谢您的帮助。

英文:

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

得分: 3

因为mgo查询返回的是文档,所以需要几行代码来实现目标:

var result []struct{ UserID int64 `bson:"userid"` }
err := coll.Find(bson.M{"isdeleted": false}).Select(bson.M{"userid": 1}).All(&result)
if err != nil {
    // 处理错误
}
userIDs := make([]int64, len(result))
for i := range result {
    userIDs[i] = result[i].UserID
}

请注意,这是一段Go语言代码,用于使用mgo库执行查询操作。它从数据库中选择未删除的文档,并将结果存储在result变量中。然后,它将result中的UserID字段提取出来,并存储在userIDs切片中。

英文:

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
}

huangapple
  • 本文由 发表于 2015年12月2日 08:11:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34032692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定