Golang Mgo通过ID(Mongodb)填充嵌套结构

Using mongoose with NodeJs for document population to simulate joins is very common. I'm trying to understand how to achieve something similar with go and mgo.

type User struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    UserName string

type MessageBoard {
    Id bson.ObjectId `json:"_id" bson:"_id"`

type Tag struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    text string

type Post struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    Text string
    MessageBoard bson.ObjectId
    User bson.ObjectId
    Tags []bson.ObjectId

I would like to store only User and Tag ids in Post. A user can have many posts and if the user edits UserName all posts should reflect this.

var posts []Post

err := PostCollection.Find(bson.M{"MessageBoard":mBoardId}).All(&posts)
if err != nil {
    return nil, err

This is a simple query to get posts, but how do I efficiently get posts with User and Tags models populated?

There is Sleep (an Mgo extension) which appears to do what I am looking for, but I am interested in understanding the performance implications and design options better and if there is a solution using Mgo alone. https://github.com/mansoor-s/Sleep


请检查有关堆栈溢出的以下问题:</ p>

如何在MongoDB中执行等效的SQL Join? </ p>

但是,并非总是必须为NoSQL数据库(例如MongoDB)模拟联接。 当需要获取所有 Post </ code>的 User </ code>时,您可能要考虑进行额外的查询或使用缓存。</ p>

PS。 即使您使用的是SQL数据库,也应仔细检查 JOIN </ code>语句,由于其潜在的性能问题,因此不建议在生产环境中使用。 </ p>
</ div>



Please check out the following question on Stack Overflow:

How do I perform the SQL Join equivalent in MongoDB?

However, it's not always necessary to simulate joins for a NoSQL database such as MongoDB. You might want to consider doing an extra query or using cache when you need to get User for all Posts.

P.S. Even if you are using SQL database, JOIN statement should be carefully reviewed and is not recommended on production, because of its potential performance issue.

Csdn user default icon