Select column from Mongodb in golang using mgo

Use the query Select method to specify the fields to return:

var result []struct{ Text string `bson:"text"` }
err := c.Find(nil).Select(bson.M{"text": 1}).All(&result)
if err != nil {
    // handle error
}
for _, v := range result {
     fmt.Println(v.Text)
}

In this example, I declared an anonymous type with the one selected field. It's OK to use a type with all document fields.


to select multiple fields:

var result []struct{
    Text string `bson:"text"`
    Otherfield string `bson:"otherfield"`
}

err := c.Find(nil).Select(bson.M{"text": 1, "otherfield": 1}).All(&result)
if err != nil {
   // handle error
}
for _, v := range result {
    fmt.Println(v.Text)
}

Tags:

Mongodb

Go

Mgo