gpt4 book ai didi

go - 如何取消引用mgo中的dbref?

转载 作者:IT老高 更新时间:2023-10-28 13:11:04 24 4
gpt4 key购买 nike

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,在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 ??

这是我的第一个 golang + mongodb,那么归档 dbref 或 joins 的最佳方式是什么?

谢谢

最佳答案

而不是使用 DBRef , 你可以使用 manual reference连接两个或多个相关文档的方法。例如,您的结构可以如下所示:

type User struct{
Id bson.ObjectId `bson:"_id"`
Name string `json:"name"`
}

type Post struct{
UserId bson.ObjectId `json:"userid"` // manual ref to User
Title string
}

然后您可以使用 $lookup aggregation stage执行左外连接。例如,要根据用户查找所有帖子:

pipeline := []bson.M{ 
bson.M{"$lookup": bson.M{
"from": "posts",
"foreignField":"userid",
"localField":"_id",
"as":"posts",
},
},
}

result := []bson.M{}
err := coll_users.Pipe(pipeline).All(&result)

示例结果:

{
"_id": ObjectId("590ab726f4bab950360c2dbe"),
"name": "test",
"posts": [
{
"_id": ObjectId("590ab72619663bad7743ff9e"),
"userid": ObjectId("590ab726f4bab950360c2dbe"),
"title": "test manual reference"
}
]
}

除了将用户和帖子存储在单独的集合中之外,您还可以嵌入/子文档。另见 Data Modelling

关于go - 如何取消引用mgo中的dbref?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32153927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com