我如何 select mgo Mongodb 中所有相同类型的嵌入文档?

How would I select all embedded documents of the same type in mgo Mongodb?

我有一个使用 mgo/mongodb 的 go 应用程序。我使用的是嵌入式文档而不是关系文档。

所以我有...(为简洁起见删节了一些代码)。

type User struct {
    Id          bson.ObjectId `bson:"_id,omitempty" json:"id"`
    Name        string        `form:"name" bson:"name" json:"name"`
    Password    string        `form:"password" bson:"password,omitempty" json:"password" binding:"required"`
    Email       string        `form:"email" bson:"email,omitempty" json:"email" binding:"required"`
    Artists     []Artist      `form:"artists" bson:"artists,omitempty" json:"artists" inline`
    Releases    []Release     `form:"releases" bson:"releases,omitempty" json:"releases" inline`
    ContentFeed []Content     `form:"content_feed" bson:"content_feed,omitempty" json:"content_feed" inline`
    Profile     Profile       `form:"profile" bson:"profile,omitempty" json:"profile" inline`
    TopTracks   []Track       `form:"top_tracks" bson:"top_tracks" json:"top_tracks" inline`
}

type Artist struct {
    Id     bson.ObjectId `bson:"_id,omitempty" json:"id"`
    Title  string        `form:"title" bson:"title" json:"title"`
    Genres string        `form:"genres" bson:"genres" json:"genres"`
}

func (repo *ArtistRepo) GetArtists() ([]Artist, error) {
    results := &[]Artist{}
    err := repo.collection.Find(???).All(results)
    return results, err
}

我试图从所有用户那里获得所有艺术家。但我不知道我的查询需要什么?我已经简要地提到了 Map/Reduce,但它似乎并不适用于我正在尝试做的事情。

我认为您假设 mgo 是一个“ORM”。但这只是在 Mongo 中存储数据的一种简单方法。有 3 种不同的方法可以解决您的问题:

  1. 将不同的类型放入不同的集合中。这样,每个文档都是相同的类型。 (集合就像关系数据库中的 "tables")。

  2. 用它的类型标记每个东西(即将对象类型存储在一个字段中),然后你可以查询它。

  3. 如果您觉得危险,可以假设所有艺术家都有流派,所有用户都有个人资料。然后使用$exists到select只有那个类型。

第一个选项是通常的做法。您应该有执行#2 或#3 的具体原因,因为它们可能会更慢。