Combine two arrays in MongoDB where neither element is null

Issue

I am looking to generate two arrays of equal length without any null elements.

Solution

I have managed to create two arrays, but they contain some null values. When I remove the null values, the arrays are no longer of equal length.

aggregate([
  {
    $unwind: '$row'
  }, {
    $match: {
      $or: [{
        'row.identifier': 'fah'
      }, {
        'row.identifier': 'agr'
      }]
    }
  }, {
    $group: {
      _id: '$row.identifier',
      rows: {
        $push: '$row.value'
      }
    }
  }
]

Current Output

[[5, null, 64, 34, 1], [53, 31, null, null, 7]]

There are still null values present in the arrays.

Desired Output:

[[5, 1], [53, 7]]

The goal is to remove null values and eliminate values at the same index.


Update 1

Provided below are examples of two documents as requested:

[{ // 1st
  row: [{
    value: 53,
    identifier: 'agj'
  }, {
    value: 51,
    identifier: 'hrw'
  }, {
    value: null,
    identifier: 'rgs'
  }]
}, { // 2nd
  row: [{
    value: null,
    identifier: 'agj'
  }, {
    value: 72,
    identifier: 'hrw'
  }, {
    value: 11,
    identifier: 'rgs'
  }]
}]

Answer №1

While I'm not very well-versed in mongodb, there may be a way to achieve filtering through that platform. Alternatively, in JavaScript, you could create a filter function similar to the one provided below:

var notNullFilter = function(inputs){
    var outputs = [];
    for (var i=0; i<inputs.length; i++){
        outputs.push([]);
    }
    for (var k=0; k<inputs[0].length; k++){
        var isNull = false;
        for (var j=0; j<inputs.length; j++){
            if (inputs[k][j] == null){
                isNull = true;
                break;
            }
        }
        if (!isNull){
            for (var l=0; l<inputs.length; l++){
                outputs[l].push(inputs[l][k]);
            }
        }
    }
};

If lodash or a similar library was being utilized, the task would be simpler. However, this function should suffice for your needs.

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

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

How can I include line breaks using HTML `<br>` tags in a textarea field that is filled with data from a MySQL

Within a modal, I am showcasing a log inside a read-only <textarea> field that contains data fetched from my MySQL database. Below this, there is a writable <textarea> field where users can input updates to the log, which are then added to the ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

Manipulating Object Properties in the Browser's Console

When I log a JavaScript object in the browser, my curiosity leads me to expand it in the console window. An example of this is: console.log(console); I discover what's inside, but then a thought crosses my mind. When I dig deeper and expand the obje ...

Storing and Retrieving Mongoose Data Using Nested Schemas, References, and Promise Functions

I have a question regarding saving and retrieving documents with nested schema references in Mongoose. When I try to save a document with nested schema refs, and then retrieve it later, the required nested field is not included unless I populate it in the ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

Managing asynchronous data using rxjs

I created a loginComponent that is responsible for receiving an email and password from the user, then making an HTTP request to retrieve the user data. My goal is to utilize this user data in other components through a service. Here is the login componen ...

The message "Temporary headers are displayed" appears in Chrome

After creating an API to remove images from a MongoDB database using GridFS, I encountered an issue when calling the API. The image is successfully removed, but it causes the server to stop with an error that only occurs in Chrome, displaying "Provisional ...

Tips for troubleshooting JavaScript errors in Internet Explorer 7 & 6 using Dreamweaver CS3

Is there a way to track and debug JavaScript errors in Internet Explorer 7 & 6 on web pages using Dreamweaver CS3? I am experienced with debugging in Visual Studio, but unsure how to do it in Dreamweaver CS3. ...

Implementing multiple functions with the onClick property of a button to validate user input

In a dialog modal, there is a text field where you can enter a title. When you click the 'create' button, it should add an item to a table and close the dialog modal. <Button onClick={createProjectButtonHandler} variant="contained"&g ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

What is the best way to extract text directly from a span element without including the text of its child nodes?

I am dealing with a piece of HTML that is dynamically generated, and it looks like this: <span> 10/10/2012 <div class="calendar"> lots of text elements here </div> </span> Is there a way to specifically retrieve the tex ...

Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/ Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it. Imagine this scenario: there's a container with content that needs to be dynamically replaced. If I wanted to repla ...

Error in clientWidth measurement providing inaccurate width

I recently adjusted the width of an image (img tag) to be 1150px * { margin: 0; padding: 0; box-sizing: border-box; user-select: none; } #background-image-myos { border: 2px solid black; border-radius: 5px; width: 1150px; } Sur ...

In ReactJS, when you encounter TextField values that are "undefined", it is important to handle them appropriately

I'm a beginner when it comes to ReactJs and Material-UI, so please bear with me if my question seems silly. Currently, I have a file named Main.js which includes the following code snippet: handleChange = (name, event) => { if(event==null) ...

Is it possible to update the event parameters with every click?

Is there a way to dynamically add a Select box for selecting a condition each time the "add" button is clicked? For example, when the add button is clicked, I would like the following elements to be continuously added: https://i.stack.imgur.com/6bad2.png ...

Having trouble establishing a connection between two Docker containers - one hosting MongoDB and the other a

Encountering trouble when trying to connect to a docker container from another container. Connectivity works fine locally outside the container, but fails when attempted from within the container. Here is the error stack trace: pymongo.errors.ServerSelecti ...

One controller, divergent template, introducing a fresh variable

I have a webpage where I showcase data (www.mysite.com/:gameId). In order to create a printer-friendly version of this data, I've set up a print page at www.mysite.com/:gameId/print. Both pages display the same information but with different designs. ...