普通网友 2016-01-06 23:22
浏览 81
已采纳

如何在mgo Mongodb中选择所有相同类型的嵌入式文档?

I have a go application which uses mgo/mongodb. I'm using embedded documents rather than relational ones.

So I have... (some code redacted for brevity).

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
}

I'm trying to get all of the artists, from all of the users essentially. But I can't figure what I need in my query? I've touched briefly on Map/Reduce, but it didn't seem to apply to what I'm trying to do.

  • 写回答

1条回答 默认 最新

  • duanduji2986 2016-01-06 23:49
    关注

    I think you are assuming mgo is an "ORM". But it's just a simple way to store data in Mongo. There are 3 different ways to fix your problem:

    1. Put different types into different collections. That way, every document is the same type. (Collections are like "tables" in a relational database).

    2. Tag each thing with it's type (i.e. store the object type in a field), then you can query on it.

    3. If you are feeling dangerous, you can assume all Artists have Genres, and all Users have a Profile. Then use $exists to select only that type.

    The first option is the usual way to do it. You should have specific reasons for doing #2 or #3, as they could be slower.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测