Searching for a value within a collection based on the key of another collection

For instance:

collectionA:
doc 1
    {
      _id:001,
      name:'Eliza',
      day:'Wednesday'
    }
doc 2
    {
      _id:002,
      name:'John',
      day:'Thursday'
    }

This example continues.. collectionB:

doc1
    {
     _id:201,
    classNames:{
              Eliza:{
               student:true
              },
              John:{
              student:false
              }
             }
    },
    {
     _id:202,
    classNames:{
              Eliza:{
               student:false
              },
              John:{
              student:true
              }
             }
    }

In the given scenario, performing a lookup is necessary. The challenge lies in having the local field as the value of the name field and the foreign field being the key of collection B. Additionally, obtaining the count is required.

Different aggregation techniques have been attempted without success thus far.

Answer №1

The inquiry may be a bit vague, however, it seems like you are looking for something along the lines of this query:

db.collA.aggregate([
  {$lookup: {
      from: "collB",
      let: {name: "$name"},
      pipeline: [
        {$project: {
            classNames: {$filter: {
                input: {$objectToArray: "$classNames"},
                cond: {$eq: ["$$this.k", "$$name"]}
            }}
        }},
        {$match: {"classNames.0": {$exists: true}}},
        {$project: {isStudent: {$first: "$classNames.v.student"}}}
      ],
      as: "classes"
  }}
])

To see a demonstration, check out the example on the playground

  • However, if your data structure is as described, it might not be the most efficient approach.

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

Using Typescript to define unions with multiple callback types

While in the process of converting my code to TypeScript, I encountered a dilemma. I created a generic foreach function that can handle arrays and objects, with different types of callbacks for iteration. However, I'm unsure how to specify the type wh ...

Child Component in Vue Not Refreshing with Prop Update

I am currently working on updating an 'exercise' prop that is being sent to a 'workout' component in Vue. Within the child component, I have set up a function to emit and increment the current set you are on. The function is successfull ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Storing Mongoose records with null sub-document collections leads to a duplicate key constraint violation

I have encountered an issue with two mongoose schemas that I am working with. var productSchema = new Schema({ name: { type: String, required: true, unique: true }, ... }); ... var categorySchema = new Schema({ ... products: [ProductSchema ...

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

What is the best way to structure a JSON object with keys that can change dynamically?

var data= [{_id: "5a93cbd49ae761a4015f6346", nombre: "Chicago - Missouri", longitud: "-94.6807924", latitud: "38.287606"}, { _id: "5a93ca539ae761a4015f6344", nombre: "Boston - Central Falss", longitud: "-71.4111895", latitud: "41.8902971"}, { _id: "5a93cc ...

Upgrading the import package alias from 'angular2' to '@angular'

Is there a way to update the package alias for import purposes? I am trying to utilize ng2-bootstrap, which requires @angular/core, but I have been referencing it as angular2/core. This mismatch is causing my screen to crash! ...

Execute asynchronous calls within each iteration and proceed to the next iteration in Node.js

I am currently faced with a dilemma at work and I need advice on the most effective approach to handle it. Below is an example of my code: for(var i =0 ;i < collection.length; i++){ asynCall( collection[i],function(){....})//doing a asynchronous cal ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Utilizing PHP configurations in JavaScript with AJAX for JSON implementation

Trying to have a config.inc.php file shared between PHP and JavaScript seems to work, but when using ajax, the "error-function" is always triggered. Is there a way to successfully share the config file with working ajax implementation? This is being utili ...

Possible reasons why Chart.js is not displaying output within a Bootstrap block

The chart on page chart.html isn't displaying the bar graph as intended. The expected output can be found at https://www.chartjs.org/docs/latest/getting-started/ Content of chart.html: {% extends "base.html" %} {% block js %} <div&g ...

What is the best way to convert the response from an XMLHttpRequest to a JavaScript array and display it

Looking to transform the data from xmlhttp.responseText into a JavaScript array I have this {"name":"Eswara Manikanta Varma","email":"contact@email.com","mobile":"9966578911"} retrieved from xmlhttp.responseText, and now I need to convert it into a JavaSc ...

There was an error in Index.js: The UserForm component did not return anything from the render function. This typically occurs when a return statement is missing. To render nothing, you can return

Hello, I'm a beginner with React and I'm attempting to add a row in my React app when a button is clicked. I referenced this guide on how to dynamically add and remove table rows in React.js However, I'm having trouble adapting it to my cod ...

invoke scrollToPosition function in React Native

I am trying to execute a function once the scrolling momentum is finished in my react native SectionList. After going through the documentation, I discovered onMomentumScrollEnd. However, the problem is that onMomentumScrollEnd only works when we manually ...

Explain the process of data binding with DOM elements

I'm intrigued by how jQuery has the ability to link arbitrary data with any DOM element without the use of HTML data attributes. $('#div_id').data('suffix', (count++)); In the Firebug HTML snapshot, I don't see any data attr ...

What is the mechanism behind the functionality of the input type=number spinner in browsers?

I want to recreate the spinner feature found in input type=number. <input type=number step=0.3/> When clicking on the up arrow of the spinner, the value increases by 0.3 (0.3, 0.6 , 0.9 , 1.2 , 1.5 ...etc). However, if the current value is 1.4 and ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

Solving the "page not found" issue in NuxtJS: A guide to fixing errors during programmatic redirects

I am currently in the process of converting a Vue project into Nuxt. I have successfully implemented a navigation guard in the app using router.beforeEach(). Upon accessing the base URL localhost:3000, I encounter the image below: https://i.sstatic.net/ ...