查询文档并选择子文档

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

Query document and select subdocument

问题

我想使用mgo选择一个子文档。
在选择之前,查询应该查询正确的顶级文档。
我尝试了以下代码:

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)

这是结构体:

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"`
}

它返回一个空的钱包文档。

英文:

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.

答案1

得分: 0

使用Query.Select(),您可以指定要检索的查询文档的字段,但是检索到的实体不会是所选字段的值,而是查询文档的值!

因此,由于您正在查询"users"集合,您应该将*User的值传递给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 {
    // 处理错误
    return
}

// 钱包在u.Wallet中
fmt.Printf("Result wallet: %+v", u.Wallet)
英文:

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)

huangapple
  • 本文由 发表于 2017年6月16日 03:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/44575225.html
匿名

发表评论

匿名网友

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

确定