duanlou2917 2015-02-06 06:33
浏览 103

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

  • 写回答

1条回答

  • dphg63476 2015-02-06 08:35
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题