Adding a modifier to multiple elements within an object

My document structure includes the following:

{
  _id: ...,
  name: ...,
  keywords: {
    group_a: [1, 2, 5],
    group_b: [4, 7, 6]
  }
}

I've figured out how to add elements to one of the elements in the keywords object like this:

db.coll.update({_id: ...}, {
  $addToSet: {
    'keywords.group_a': {
      $each: [9, 12, 17]
    }
  }
})

But is there a way to add the same set of elements to both group_a and group_b? Perhaps something similar to

db.coll.update({_id: ...}, {
  $addToSet: {
    ['keywords.group_a', 'keywords.group_b']: {
      $each: [9, 12, 17]
    }
  }
})

Even though the above code isn't valid, I am looking for a solution where I can specify the names of the groups in advance and add the elements to all of them simultaneously.

Answer №1

If you want to apply the same values to multiple fields using the $addToSet operator, you can do it in the following way:

db.collection.update({_id: ...}, {
  $addToSet: {
    'category.type_a': {
      $each: [7, 14, 21]
    },
    'category.type_b': {
      $each: [7, 14, 21]
    }
  }
})

To make your code more efficient and concise, you can simplify it like this:

var each = { $each: [7, 14, 21] };
db.collection.update({_id: ...}, {
  $addToSet: {
    'category.type_a': each,
    'category.type_b': each
    }
  }
})

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 method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. https://i.sstatic.net/xQBO ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

NodeJS is facing a severe challenge in properly rendering HTML and its accompanying CSS code, causing a major

Once upon a time, I built a beautiful website while practicing HTML, CSS, and JS. It had multiple web pages and used Express for the backend. Unfortunately, I lost all the files associated with it and took a break from web programming for some time. Now, w ...

The elusive username remains undefined despite having meticulously defined the schema and model

I'm struggling with an error in my code and would appreciate some help debugging it. The issue I'm facing is that even though I have defined my user schema, it is still showing as undefined. I've spent a considerable amount of time trying to ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Tips for accessing the value of a DOM node during the first render

I am attempting to extract a value from an input textbox during the initial rendering process using useRef, but I am encountering the following error: " ref is not a prop. Trying to access it will result in undefined being returned. If you need to ac ...

Displaying Material UI textboxes in multiple columns for dynamically created forms using ReactJs from an array

I am working with an API to retrieve a list of cars, and I have come up with the following code snippet to generate labels and textboxes for editing the car codes. {!carQuery.loading && carDefinitions?.map((car: ICarType, idx: number ...

What is the best way to fill an array of ids using mongoose?

I attempted to populate an array of object IDs, but it is not functioning correctly Mongoose Object const Schema = mongoose.Schema; const OrderSchema = new Schema({ products: [{ product: { type: Schema.Types.ObjectId, ref: 'Product'}, ...

req.user not being passed to React

I have a route where I retrieve a decision from mongoose, but I also want to include the logged in userId in the JSON response. Despite seeing it in Postman, I can't seem to get this value to reflect in the res.data object in React. // Postman test e ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Difficulty with MultiHandleSliderExtender and postback in JavaScript

Attempting to implement the multihandlesliderextender (from the Ajax Toolkit) for creating a price filter option on a webshop. Upon selecting a new price, it should trigger a reload of everything including extensive behind-the-scenes code. Referenced an a ...

Error: Selenium-Javascript tests encountering an unexpected token issue

Having worked with Selenium using Java for a long time, I decided to switch gears and start writing Selenium scripts in JavaScript. I found a helpful guide to learn JavaScript with Selenium, which you can check out here. However, when I attempted to run n ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

Creating an object in C++ and utilizing it in QML

Is it possible to use a factory class in C++ to create objects that can be accessed in QML? How can I access a newly created object in QML using JavaScript? In my C++ factory class, I have implemented the creation of an employee object, which can be of ty ...

How to handle JSON parsing in a sails.js controller with node.js

Within my MapController, I have created a function to parse remote JSON files and populate an array called "parsewebservice" through an if-else structure. While everything seems to be working fine, the issue arises when trying to log the values of parseweb ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Exploring the concept of utilizing named arguments within Express.js routing

I've searched extensively, but can't seem to find any information on this topic. My goal is to create requests like the following: url/list/message=hello?id=1234 Despite my efforts, I have not come across any resources on how to achieve this us ...

Disabling a button based on the state of a switch button using React and Material UI

For the task at hand, we need to ensure that the button is only activated when the switch button's state changes. This state is received as a prop and needs to be validated correctly within the handleChangeState function. const CustomSwitch = ({name, ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...