Search code examples
selectgomgosubdocument

Query document and select subdocument


I want to select a subdocument using mgo. Before select, the query should query the right top level document. I tried this:

name := "anything"
w := models.Wallet{}
c := s.DB("ep2").C("users")
err := c.Find(bson.M{"name": name}).Select(bson.M{"wallet": 1}).One(&w)

These are the structs:

type User struct {
    Id     bson.ObjectId `bson:"_id,omitempty" json:"-" form:"-"`
    Wallet Wallet        `bson:"wallet,omitempty" json:"wallet,omitempty" form:"wallet,omitempty"`
} 

type Wallet struct {
    Taddr     string  `json:"taddr,omitempty" form:"taddr,omitempty"`
    TaddrPriv string  `json:"-" form:"-"`
    Tbalance  float64 `json:"tbalance" form:"tbalance,omitempty"`
}

It returns an empty wallet document.


Solution

  • With Query.Select() you may specify which fields of the queried document(s) you want to retrieve, but the retrieved entities will not be the values of the selected fields, they will still be the values of the queried documents!

    So since you are querying the "users" collection, you should pass a value of *User to Query.One():

    name := "anything"
    u := models.User{}
    c := s.DB("ep2").C("users")
    err := c.Find(bson.M{"name": name}).Select(bson.M{"wallet": 1}).One(&u)
    if err != nil {
        // Handle error
        return
    }
    
    // Wallet is in u.Wallet
    fmt.Printf("Result wallet: %+v", u.Wallet)