What is the method for determining the active configuration?

I am working with a MongoDB database that consists of 3 collections. Each collection is exemplified below by a document:

tag

_id: ObjectId('61b873ec6d075801f7a97e18')
name: 'TestTag'
category: 'A'

computer

_id: ObjectId('6098c5ab615d9e23543d0f6f')
name: 'TestComputer'
category: 'A'
tags: [
    'TestTag'
]

setting

_id: ObjectId('61e56339b528bf009feca149')
name: 'FirstSetting'
category: 'A'
priority: 1
tags: [
    ObjectId('61b873ec6d075801f7a97e18')
]

_id: ObjectId('61e56339b528bf009feca150')
name: 'SecondSetting'
category: 'A'
priority: 2
tags: [
    ObjectId('61b873ec6d075801f7a97e18')
]

The main concept here is that a tag can be created and used to tag computers and settings, but only within the same category:

For instance, a tag with the category 'A' can only be attached to computers and settings of category 'A'

A computer can have only one active setting at a time. The active setting is determined by the tag they share. If a device shares tags with multiple settings, the one with the highest priority takes precedence.

So, following these guidelines, I aim to include a new activeSetting property to each device, as shown below:

computer

_id: ObjectId('6098c5ab615d9e23543d0f6f')
name: 'TestComputer'
category: 'A'
tags: [
    'TestTag'
]
activeSetting: ObjectId('61e56339b528bf009feca149')

My Attempt:

I have attempted to use lookup to retrieve lists of computers and settings for each tag, but I am unsure what steps to take next.

Answer №1

Try this approach:

db.computer.aggregate([
  {$match: {_id: ObjectId("6098c5ab615d9e23543d0f6f")}},
  {$lookup: {
      from: "settings",
      localField: "category",
      foreignField: "category",
      pipeline: [
        {$sort: {priority: 1}},
        {$limit: 1},
        {$project: {_id: 1}}
      ],
      as: "activeSetting"
  }},
  {$set: {activeSetting: {$first: "$activeSetting._id"}}}
])

Test it out yourself on the interactive playground

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

The fetch() function is inundating my API with an overwhelming amount of requests

After implementing the following function to retrieve images from my API, I encountered an issue: function getImages() { console.log("Ignite"); fetch('https://api.itseternal.net/eternal/stats', { headers: { & ...

Unveiling concealed content with JQuery

Here is a link to my pen: http://codepen.io/anon/pen/IszKj I am looking to achieve the functionality where clicking on either "any status" or "any date" will reveal a hidden div containing a list of options. My main query is about the best approach to ta ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Update the state both before and after executing the API call

I'm facing an issue with the setState function where it seems to be getting called again before completing the previous batch of state updates. My data object has the following structure: [{ id: 0, loading: false }] On my webpage, I have toggle butt ...

Include the library path in the .htaccess file for Codeigniter

Currently, I am working on a project that involves Codeigniter and MongoDB. Since affordable hosting for MongoDB is hard to come by, I have opted to use MongoLab, which offers free MongoDB space while hosting the project on another server. MongoLab provide ...

`Erase content from a field once text is typed into a different field`

I have a Currency Converter with two input fields and a button. I enter the amount to be converted in the first field, and the result of the conversion appears in the second field. My question is: How can I automatically clear the second field when I type ...

What is the method for developing a Typescript-connected High-Order React Component with Redux?

I am looking to develop a React Higher-Order Component that can safeguard routes within my application from unauthorized users without an access token. I aim to use this HOC to wrap a Component like so in the parent component: <Route exact path ...

Pairing a removal request with a JSON entity

I am currently working on a project where I need to delete a specific JSON object from a JSON file once its values are displayed in a form using the AJAX Delete function. In order to achieve this, I have set up a route in Express for the JSON file as shown ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

How can I stop jQuery from repeatedly appending content every time I click the button?

Hey there, I have a question about calling a JSON array using jQuery. Every time I press the button, it loads the list again instead of multiplying. Here is the JSON array: [{"denumire":"Q Club"},{"denumire":"Carul cu Flori"},{"denumire":"La Rocca"}] And ...

Tips for speeding up page loading when using the same image multiple times on a page

Is it possible to utilize a JavaScript Image object? If yes, could you provide an illustrative example? And is it feasible to achieve this with jQuery? ...

Selected jQuery plugin is not updating HTML select option

I've been attempting to update the select tag in my HTML file to match the style used in the example on the Chosen v1.8.7 website, but despite following the instructions, the select element remains unchanged: test.html <head> <link rel=& ...

In a React app, there are instances where `localstorage.getitem('key')` may result in returning null

I've encountered a strange issue while building a login form that sets a JWT token in localstorage. The problem arises when, despite being able to see the token in my console.log, setting localstorage.getitem('idToken') sometimes returns nul ...

The outcome is not displayed in the appropriate section of the text

There seems to be an issue as the console is not displaying the response to the input, such as "the answer is correct" or "the answer is either empty or incorrect". <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</ ...

What is the best way to customize the appearance of chosen selections in the MUI Autocomplete component?

I'm currently facing an issue with changing the style of selected options in MUI when the multi option is enabled. My goal is to alter the appearance of all highlighted options. Any assistance on this matter would be greatly appreciated, thank you! ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

What is the ideal event to trigger a response when the user completes entering text into the search field in Vue.js?

I am currently utilizing a text field from the Vuetify library to filter a table within my application. <v-text-field style="min-width: 300px;" v-model="filterString" label="Search" /> The functionality is straigh ...

How to use Mongoose to update a MongoDB document with multiple arrays of nested documents

If I have a document structured like the following: { "personId": 13998272, "address": [ { "addressType": "HOME", "streetNo": 21, "addressLine1": "LORRAINE AVENUE", "addressLine2": "EDGEWATER", "city": "KINGSTON", ...