普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?