var (
type User struct{
Id bson.ObjectId `bson:"_id"`
Name string
}
type Post struct{
Id bson.ObjectId `bson:"_id"`
Uid string
User User
ref mgo.DBRef
Title string
}
)
//try 10000 times inserts
id := bson.NewObjectId()
user := &User{ id, "test"}
db.C("users").insert(user)
post := db.C("Post").insert(&Post{Uid: id.hex(), ref: mgo.DBRef{"ref":"users", "id": id}, Title:"test dbref"})
//first way so dirty -_-!
//mysql: left join users on user.id=post.uid, how to do in mgo ?
posts := new([]User)
db.C("posts").Find(nil).All(posts)
ids := []bson.ObjectId
for _, p := range posts{
ids = append(ids, p.Uid)
}
users := make([]User, len(ids))
db.C("users").Find(bson.M{"_id": {"$in": ids}}).All(users)
//and then set the User attribute?
for _,u := range users {
for _, m := range m{
if m.Uid == u.Id {
m.User = m
}
}
}
secondary way,with ref attribute, but mgo.session will try to findid
for _,m := range posts{
db.FindRef(m.ref).One(&m.User)
}
//3th way, with mapReduce ??
it's my first golang + mongodb, so what is the best way to archive dbref or joins?
Thx