Mgo populate nested structs by ID (Mongodb)

71 views
Skip to first unread message

Craig Sennabaum

unread,
Feb 6, 2015, 1:58:17 AM2/6/15
to mgo-...@googlegroups.com

I just asked the following on StackOverflow but figured I would add it here as well 

http://stackoverflow.com/questions/28359882/golang-mgo-populate-nested-structs-by-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

Gustavo Niemeyer

unread,
Feb 9, 2015, 11:00:58 AM2/9/15
to mgo-...@googlegroups.com
Hi Craig,

On Fri, Feb 6, 2015 at 8:58 AM, Craig Sennabaum <csenn...@gmail.com> wrote:
(...)
> This is a simple query to get posts, but how do I efficiently get posts with
> User and Tags models populated?

The answer is straightforward, which perhaps means the question is not
clear to me: you can use exactly the same syntax to get any other
field:

err := posts.Find(bson.M{"user": userId}).All(&all)

and

err := posts.Find(bson.M{"tags": tagId}).All(&all)


Please note that using All may not be ideal in this case. If the query
matches thousands of posts, they'll all be put in memory at once,
which may exceed the available memory.


gustavo @ http://niemeyer.net
Reply all
Reply to author
Forward
0 new messages