Performing complex joins in MongoDB using multiple sub documents

I am managing two unique collections,

Users collection:

{
    "userId": 1,
    "name": 'Alice',
    "profile": 'alice.png'
},
{
    "userId": 5,
    "name": 'Bob',
    "profile": 'bob.png'
},
{
    "userId": 10,
    "name": 'Carol Smith',
    "profile": 'carol.jpg'
}

Posts collection:

{
    "postId": 3,
    "userId": 1,
    "postContent": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
    "comments": [
        {
            "comment": "Great post!",
            "commentedBy": 5,
        },
        {
            "comment": "Love this!",
            "commentedBy": 10,
        }
    ],
}

How do I retrieve post details along with user information for each post and user details for each comment using a single mongoose query?

Answer №1

If you're looking to connect your collections in Mongoose, the "populate" method is a great tool to use. Check out the documentation here: https://mongoosejs.com/docs/populate.html

This feature allows you to easily link your collections in the schema definition and query and populate all related collections with just one query, like so:

Posts.findOne({ postId: 1 }).populate('user')

For more information on how to set up your Schemas, make sure to visit the link provided above.

Answer №2

To achieve this, you can utilize the combination of $aggregate and $lookup

db.posts.aggregate(
  [
    {
      $lookup:
      {
        from: "users",
        localField: "userId",
        foreignField: "userId",
        as: "users"
      }
    }
  ]
).pretty()

The result will be displayed in the following format:

{
        "_id" : ObjectId("5ecceb468d4390391825b79d"),
        "postId" : 1,
        "userId" : 1,
        "postContent" : "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
        "comments" : [
                {
                        "comment" : "sample comment",
                        "commentedBy" : 2
                },
                {
                        "comment" : "Another sample comment",
                        "commentedBy" : 3
                }
        ],
        "users" : [
                {
                        "_id" : ObjectId("5ecceb168d4390391825b79a"),
                        "userId" : 1,
                        "name" : "John",
                        "profile" : "john.png"
                }
        ]
}

Information sourced from MongoDB

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure that MongoDB Node JS uses Int32 - Int64 instead of Double?

Is there a way to save integer values as int32 or int64 in my Atlas Trigger (NodeJS code)? Currently, when I save any value, it is saved as a Double instead. user_collection.updateOne({"_id": "anyID"}, {$inc: {"score": 2}}); ...

Detecting slopes using THREE.js

Can someone please advise on how to properly detect slopes in a car game? I want the car to recognize the slope as such, rather than mistaking it for a collision object. I've been looking everywhere for answers but have yet to come across anything use ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

What is the best way to sort in Mongodb by score first, and then by time if there is a "tie"?

results = docDB.posts.find({"active":True }).sort("pop_score", pymongo.DESCENDING) Currently, I am using this sorting method. However, I encountered an issue where some items have the same "score". When they are tied, I would like them to be sorted based ...

Order dates within an array by year in descending order, followed by arranging by month in ascending order, and then sorting

Upon receiving data from an AJAX to PHP call, I am presented with an array containing information about classes and the dates they were offered. Let's refer to this array as 'data': var data = [{ "course": "Mathematics", "courseDate": " ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...

What is the best way to trigger an event function again once a specific condition has been satisfied?

I'm currently working on a project where I need a sidebar to scroll at a slower rate until it reaches a specific point, and then stop scrolling once that point is reached. Below is the jQuery code I've been using: $(window).on("scroll", function ...

Steps to implement jQuery after executing the command "npm install jquery"

Greetings! I recently utilized npm install jquery to add jQuery to my project. However, I noticed that it was downloaded into node_modules\jquery along with some unnecessary files. My goal is to only move node_modules\jquery\dist\jquer ...

Send a string variable from PHP to a JavaScript function

Struggling to transfer a string from a PHP page to a JavaScript function on another page. This is for showing a message after checking if the item being added already exists in an array. I've attempted using quotes and not using quotes in the alert s ...

Error encountered while using Chart.js with JSON dataset

Struggling to make this work... Here are the necessary scripts: <script src="Chart.js"></script> <script src="jquery-1.11.3.min.js"></script> This is the full code I am working with: <body> <div id="chartCanvas"> &l ...

Having trouble establishing a connection to the PostgreSQL database using Node JS/Express. Not receiving any response when making the request in Postman

Previously, the port was operational and running, but there was no response in Postman. Now, even though Express is included, it fails to be recognized. Can someone please assist me? I've been grappling with this issue for days now... I attempted to ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

Guide on successfully importing PDF files in NextJS using Webpack's file-loader without encountering a 404 error

I'm working on my nextjs app and I'm trying to implement a button that, when clicked, downloads a PDF file. I've stored the PDF in public/documents/, imported it, and added it to the link href. However, when I click on the button, I'm e ...

Efficiently rendering a million elements on an HTML canvas (and replicating the render from the server)

I'm currently working on developing an HTML application using a canvas as the base. The canvas will consist of a large grid, around 1500 x 700 in size, totaling to over 1 million cells. The main concern is how to efficiently render this grid without ...

What is the best way to access the URLs of files within a Google Drive folder within a React application?

I've been working on a react app that's relatively straightforward, but I plan to add a gallery feature in the future. To keep things simple for the 'owner' when updating the gallery without implementing a CMS, I decided to experiment ...

Swap information in one array with information from a different array

I am working with two arrays: const data = [ { id: 0, identifier: 'free-2020', name: '<I18nText id="pricing.plans.name.free" />', planTitle: 'free', price: '00', ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Use Javascript to extract an array of strings enclosed in double quotes

Is there a way to extract an array containing ["13139","13141", "13140"] from the following data structure? { "13139": [tx[0]], "13141": [tx[1]], "13140": [tx[2]] } I attempted to use JS ...