Create a new array by adding keys and their values to multiple documents

In my collection named inventory, I have multiple documents with values for each document.

{ "apples": 2 ,"oranges": 3,  "carrots": 5 }
{ "apples": 4, "oranges": 6, "carrots": 9 }

How can I combine all the fruits into a single array in multiple documents like this:

{ "fruits": { "apples":2 ,"oranges":3 }, "carrots": 5 }

Answer №1

It's important to note that the example provided is not an array in MongoDB, but rather a sub-document for "fruits" with different keys. An actual array in MongoDB would be structured like this:

{ "fruits": [{ "apples":2 } , { "orange":3 }], "carrot": 5 }

In addition, the term "fruits" is subjective as it requires specifying a list of items considered fruits. Another aspect to consider is that MongoDB currently does not have a direct way to reference the existing value of a field when updating.

This means you'll need to use .find() to retrieve the data from each document in order to restructure it. Essentially, this involves looping through results and performing an .update() operation on each document.

The Bulk API introduced in MongoDB 2.6 can assist with batch writing operations to the database instead of one at a time:

// Code snippet mentioned here

This code snippet utilizes the $each modifier for $push to add multiple array entries simultaneously. The $unset operator can safely be used for fields that don't exist in the document without needing to check their presence beforehand.

If you specifically require a document structure similar to the given example (which is not an array), you can construct it using the $set operator:

// Code snippet for constructing non-array document

Regardless of the approach, looping through the existing collection is necessary. There isn't a direct operation in MongoDB to extract an existing value in a document and use it to set a new value from the server-side perspective.

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

Having trouble retrieving text from the data attribute

I have a Bootstrap Table with an edit button on each row. I've implemented a data formatter to include the record ID as a data attribute that should be accessible when the button is clicked. Oddly, while inspecting the element in the console shows tha ...

I am looking to dynamically alter the CSS background URL using JavaScript

Currently, I am looking to update the background image url using JavaScript. Most tutorials I've come across involve having the image downloaded on the desktop and then providing its path. However, in my scenario, the user will input an image link whi ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Ways to divide a buffer in JavaScript

String was created by utilizing the toString method on the buffer. Here is a sample of the resulting string: GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 .... Is there a way to parse this string whenever a space (" ...

Display or conceal several elements upon hover using JQuery and HTML

Here is the current progress I have made: <div style = "position: relative;"> <a href = "#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "positio ...

What is the best way to have a form open upwards when hovered over or clicked on?

Attempting to create a button in the bottom right corner that will reveal a form when clicked or hovered over. The form should slide open slowly and close after clicking on login, but currently the button is moving down as the form opens. The button also ...

What could be the issue with trying to bind an event handler in this manner?

I'm having some trouble binding an event handler with jQuery: $(document).ready(function () { var newsScrollerForPage = new NewsScroller(); newsScrollerForPage.init(); $('#scroller-left-a').bind('on ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

A tutorial on dynamically adding fields with a dropdown list (populated from a database) and a text box using PHP and JQuery

I have multiple form components that I need to add dynamically, allowing users to add more than one. Firstly, there is a dropdown list with values populated from MySQL, followed by a text box for inquiries entry. The dropdown list displays a list of users, ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

Tips on adding an item to an array in Mongoose (issue)

I am currently configuring a route in a Node server using Mongoose and Mongo that adds a comment to the comments array in a blogPost model (I will share the model code below). However, when attempting to run the query, I encounter the following error: Post ...

Collapse in Bootstrap 3 Navigation Bar

I'm really struggling to understand why my navbar is refusing to collapse. I've included the necessary Bootstrap CSS and JS files, as well as the transition and collapse JS files. Below is the code that I've been working with. Any assistance ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Every time I try to import my Node router in my Node.js application, it leads to a

I'm experiencing a crash on my Node.js server when I try to import the node routes. Strangely, removing the routes resolves the issue. I've spent time trying to pinpoint the problem without success. Upon double-checking, the path appears to be co ...

Having trouble accessing the true "valid" property within a function utilizing ref and VeeValidate

In my code, I am using a <ValidationObserver ref="observer"> with several ValidationProviders inside. In order to access the "valid" property of a specific field named "Unit" in the method getUnit(), I currently use this.$refs.observer.fields["Unit"] ...

Using regular JavaScript with code inside ng-view in AngularJS involves incorporating event listeners and manipulations that can interact

Just delving into the world of angularJS for the first time. I've set up the routing service, which involves having a div with routing that calls in a template containing HTML code. I also have a range of regular JavaScript functions necessary for the ...

Troubleshooting: Why is jQuery Autocomplete failing to function with JSON PHP to JavaScript integration?

I need to implement an AutoComplete feature with a list of countries from a SQL database. 1. Using PHP: $sql_list_countries=(SQL request) var_dump: array (size=2) 0 => object(stdClass)[3] public 'meta_value' => string &apos ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

We're sorry, but Nest is unable to fulfill the dependencies of the movieModel. Kindly ensure that the DatabaseConnection parameter at index [0] is accessible in order for the process

I am facing an issue while using mongoose in Nest.js The error message I received is as follows: Nest can't resolve dependencies of the movieModel (?). Please ensure that the argument DatabaseConnection at index [0] is available in the MongooseModul ...