What is the best way to merge three collections without using $unwind and generate a nested outcome depending on a specific condition?

People Database:

[
  {
    "_id": ObjectId("5f3258cfbaaccedaa5dd2c96"),
    "gender": "male",
    "name": {
      "title": "mr",
      "first": "victor",
      "last": "pedersen"
    },
    "location": {
      "street": "2156 stenbjergvej",
      "city": "billum",
      "state": "nordjylland",
      "postcode": 56649        
    },
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8a959f88938ed28c9998998e8f9992bc99849d918c9099d29f9391">[email protected]</a>"
  }
]

PersonDetails Database:

{
    "_id": ObjectId("5f3a91e68b1c26e68f9ed3ad"),
    "country": "India",
    "personid": ObjectId("5f3258cfbaaccedaa5dd2c96")
}

CountryDetails Database:

{
    "_id": ObjectId("5f3fc2aa9532398a037ff7ae"),
    "country": "India",
    "continent": "Asia"
}

One individual can have multiple person details and each person detail may have several country details.

Query: Retrieve Person, persondetails, and countrydetails for countries in Asia continent.

The output should be like:

[{
    "_id": ObjectId("5f3258cfbaaccedaa5dd2c96"),
    "gender": "male",
    "name": {
        "title": "mr",
        "first": "victor",
        "last": "pedersen"
    },
    "location": {
        "street": "2156 stenbjergvej",
        "city": "billum",
        "state": "nordjylland",
        "postcode": 56649
    },
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="493f202a3d263b67392c2d2c3b3a2c27092c31282439252c672a2624">[email protected]</a>",
    "persondetail": [{
        "_id": ObjectId("5f3a91e68b1c26e68f9ed3ad"),
        "country": "India",
        "personid": "5f3258cfbaaccedaa5dd2c96",
        "countrydetail": [{
            "_id": ObjectId("5f3fc2aa9532398a037ff7ae"),
            "country": "India",
            "continent": "Asia"
        }]
    }]
}]

Note: This needs to be done with aggregate()

My unsuccessful try :

db.persons.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          "$_id",
          {
            "$toObjectId": "5f3258cfbaaccedaa5dd2c96"
          }
        ]
      }
    }
  },
  {
    $lookup: {
      from: "persondetails",
      localField: "_id",
      foreignField: "personid",
      as: "persondetail"
    }
  },
  {
    $unwind: {
      "path": "$persondetail",
      includeArrayIndex: "arrayIndex",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $lookup: {
      from: "country",
      localField: "persondetail.country",
      foreignField: "country",
      as: "countrydetails"
    }
  },
  {
    "$match": {
      "$expr": {
        "$eq": [
          "$persondetail.continent",
          "Asia"
        ]
      }
    }
  }
])
 

The above code does not execute as expected, and even if corrected, unwind would result in a flat structure, contrary to the desired outcome.

Answer №1

If you want to include nested lookups in your queries, you can utilize the $lookup feature with a custom pipeline:

{
    $lookup: {
       from: "persondetails",
       let: { person_id: "$_id" },
       pipeline: [
           {
               $match: {
                   $expr: { $eq: [ "$personid", "$$person_id" ] }
               }
           },
           {
               $lookup: {
                   from: "countrydetails",
                   localField: "country",
                   foreignField: "country",
                   as: "countrydetail",
               }
           }
       ],      
       as: "persondetail"
    }
}

Visit Mongo Playground for more details

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

Are socket.io and websocket secure for integration with an express server?

I am interested in creating a real-time system using express and recently learned about socket.io and websockets. However, I have concerns about the security of using const io = socket.io("https://example.com");. Since the socket connection URL is accessib ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

Tips for adding an array of objects into a MariaDB database

My MariaDB table is quite simple, consisting of 3 columns: DT as the primary key Savings kpd https://i.stack.imgur.com/8p9YA.png I am looking to efficiently insert a large array of objects into the table at once. Here is a snippet of how the data looks: ...

What is the correct approach to hiding problems in Flow NPM packages to ensure that end-user applications do not encounter any errors?

When utilizing something like $FlowIssue, it cannot be ensured that it will be included in every .flowconfig file. Defining a library interface appears to only function within the specific project and not in other projects that import the package (even if ...

Pass data to all routes in ExpressJS

After logging in, I am setting req.session variables as follows: req.session.loggedin = true req.session.firstname = loginDetails.firstName; I would like to streamline this process and pass this information to ALL routes without manually adding them to ea ...

Efficiently Transmitting JSON Data via HTTP Requests

I have the following: Route file "prontuarios.js": module.exports = function(app){ getProntuarios = function(request, response, next){ var sqlCustom = request.query; var connection = app.infra.connectionFac ...

While running on Windows 10, I attempted to execute the command "yarn add protobufjs" but encountered an unexpected issue. The error message displayed was: "An unexpected error occurred: E

After running the command yarn add protobufjs on my Windows 10 operating system, I encountered the following error message: \**>yarn add protobufjs [1/4] Resolving packages... [2/4] Fetching packages... error An unexpected error occurred: "EPERM: ...

Building a system with distributed subscribers in Node.js using Google Pub/Sub

We are facing challenges migrating our message processing application from Kafka to Google Pub/Sub, as the transition is not going as smoothly as expected. Operating within Kubernetes on Google Cloud, we have multiple pods concurrently handling messages o ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

When utilizing Monggose, Angular, and Node, a route containing the deleteOne method repeatedly reports that the object has been successfully deleted, despite the delete count remaining

I've encountered a similar issue to others, but their solutions didn't work for me. I'm working on a small MEAN app with mongoose and facing a problem when trying to delete a user or any other object stored in the collection. The route seems ...

Developing permanent links using Express and MongoDB

Imagine I have designed the following database schemas for a Learning Management System (LMS) application: const CourseSchema = new mongoose.Schema({ name: { type: String, required: true }, code: { type: String, required: true, unique: 1, uppercas ...

Unveiling computer bots and spamming with Express JS

I've scoured the internet but have been unable to find a framework that specifically deals with identifying and blocking spamming computers and users who are trying to access my server's data. I am in need of an expressjs/nodejs solution that can ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

Node.js encountered a SyntaxError due to an unexpected token "{" being found in

Currently, I am going through a tutorial and having trouble understanding this error. Despite double-checking everything, I believe my lack of experience is the root cause of the issue... An Unexpected token { SyntaxError occurred: at new Script (vm.j ...

Is it achievable to create a nested query builder in AdonisJs using Lucid ORM?

Is it possible to perform a nested ".scope" query using Lucid in AdonisJs? I am trying to retrieve all Orders that do not have the 'd' status in OrderItems for a specific Office (similar to Laravel's whereHas('orders.items')). For ...

Turn off the serving of static assets in Sails.js

Is there a way to disable serving static assets completely in the configuration settings? I'm wondering if simply adding an empty folder and specifying it in the custom express middleware is the right approach: module.exports = { // Initialize custo ...

Node.js with JSDOM exits smoothly without loading any unnecessary resources

I've been following a tutorial on this amazing site: Currently, I'm struggling to make the final step work. Initially, I attempted this with my own code as I am starting to grasp the concepts of using node and express. However, I encountered th ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Troubleshooting common issues while setting up React Native with TypeScript

After carefully following the steps outlined in this guide on configuring a React Native project using TypeScript: https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native, I encountered a total of fifteen errors from the ...

Unexpected Token in JSON parsing using NPM

I've been attempting to set up grunt, but it's not working out for me. npm install -g grunt-cli --registry http://registry.npmjs.org/ When I run the above command, I encounter the following error: npm ERR! registry error parsing json npm ERR! ...