MongoDB - How to perform joins as in relational databases

Viewed 27

As you may have guessed, I am from the RDBMS background.

I have made a document model in MongoDB. The simple representation would be like:

Collection users

{
  "_id": <ObjectId>,
  "name": "Simon",
  "photo": "https://...jpg"
}

Collection: Posts

{
  "_id": <ObjectId>,
  "author": ObjectId(<AdIdFromUsers>),
  "likes": [ ObjectId(<AdIdFromUsers>), ObjectId(<AdIdFromUsers>) ],
  "comments": [
    {
      "author": ObjectId(<AdIdFromUsers>),
      "content": "Hi everyone!",
      "likes": [ ObjectId(<AdIdFromUsers>), ObjectId(<AdIdFromUsers>) ],
      "replies": [
         {
            "author": ObjectId(<AdIdFromUsers>),
            "content": "Hi everyone!",
            "likes": [ ObjectId(<AdIdFromUsers>), ObjectId(<AdIdFromUsers>) ],
         }
       ]
    }
  ]
}

I have read from mongodb docs that it's okay to use Manual Reference in most cases.

But my question here is, How can I optimize this to make hundreds of requests to the database to get information about a post? Like:

  1. Get the post document first
  2. Then loop through the comments and replies and get author info
  3. Loop through likes and get each user

Please feel free to correct me if I'm taking the wrong approach

1 Answers

From my experience it is totally normal in my opinion. I am doing it the same way. In my back-end when I want to get multiple sub documents from my actual document, I go through a for loop, collect the info, store it in a array and then return the response to the user.

Here are some advantages:

  • You don't have to create a separate collection for every type of document you have
  • From my knowledge it is somewhat slower but should definitely do the job
  • You can keep all the info in one place
Related