我如何找到文档的数组,只获取数组

时间:2013-12-23 09:15:56

标签: mongodb find

  • 数据库MongoDB
  • 程序语言Golang
  • 数据驱动mgo

文档结构

type Organizations struct {
Id bson.ObjectId `json:"_id"`

Name         string `json:"name"`
Area         string `json:"area"`
Type         string `json:"type"`
CustomerType string `json:"customertype"`
State        string `json:"state"`
LastUpdated  string `json:"lastupdated"`
Assigned     string `json:"assigned"`

Address `json:"address"`
}

属于组织的阵列结构

type Sections struct {
Name        string `json:"name" bson:"name"`
Upper       string `json:"upper" bson:"upper"`
Master      string `json:"master" bson:"master"`
Uppermaster string `json:"uppermaster" bson:"uppermaster"`

OrgID bson.ObjectId `json:"orgid"`
}

我的查询命令

result := []Sections{}

collection.Find(bson.M{"_id": bson.ObjectIdHex(orgid), 
        "sections": bson.M{"$exists": true}}).All(&result)

最后,我得到一个带数组的文档。

但是,我只想获取文档中“Sections”数组的数据。

我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:0)

我不懂Go语言+ mgo语法,但我想你可以想出类似的东西

db.collection.find({_ id:orgid,sections:{$ exists:1}},{_ id:0,sections:1})


检查预测是如何完成的 http://docs.mongodb.org/manual/reference/method/db.collection.find/#projections