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.
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:
Put different types into different collections. That way, every document is the same type. (Collections are like "tables" in a relational database).
Tag each thing with it's type (i.e. store the object type in a field), then you can query on it.
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.