Search code examples
mongodbgounmarshallingmgo

Golang mgo result into simple slice


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.


Solution

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