Utilizing the power of Mongodb's aggregation feature with the $add

I'm facing a roadblock in my mongodb aggregation process. Within the mongodb document, there is an array called details.

{
    user: "userName1",
    details: [{
        adminId: "admin123",
        id: "1",
        name: "name1",
        available: true,
        address: "address1"
    }, {
        adminId: "admin123",
        id: "2",
        name: "name2",
        available: false,
        address: "address2"
    }]
}

The task at hand is to compare the following data with the details in the document and add those entries that are not present in the details using aggregation:

// comparing data
data = [{
        adminId: "admin123",
        id: "1",
        name: "name1",
        address: "address1"
    },{
        adminId: "admin123",
        id: "2",
        name: "name2",
        address: "address2"
    },{
        adminId: "admin123",
        id: "3",
        name: "name3",
        address: "address3"
    },{
        adminId: "admin123",
        id: "4",
        name: "name4",
        address: "address4"
    }]

This is the desired output after performing the aggregation:

// expected response from database after aggregation
{
    user: "userName1",
    details: [{
        adminId: "admin123",
        id: "1",
        name: "name1",
        available: true,
        address: "address1"
    },{
        adminId: "admin123",
        id: "2",
        name: "name2",
        available: false,
        address: "address2"
    },{
        adminId: "admin123",
        id: "3",
        name: "name3",
        address: "address3"
    },{
        adminId: "admin123",
        id: "4",
        name: "name4",
        address: "address4"
    }]
}

Answer №1

https://example.com/aggregation-query

If you want to compare data and find matches, you can use the following aggregation method. It first iterates through the data to compare and if a match is found, it takes the matched one; otherwise, it uses the data being compared.

db.collection.aggregate([{
        "$addFields": {
            "data": [{
                    adminId: "admin123",
                    id: "1",
                    name: "name1",
                    address: "address1"
                },
                {
                    adminId: "admin123",
                    id: "2",
                    name: "name2",
                    address: "address2"
                },
                {
                    adminId: "admin123",
                    id: "3",
                    name: "name3",
                    address: "address3"
                },
                {
                    adminId: "admin123",
                    id: "4",
                    name: "name4",
                    address: "address4"
                }
            ]
        }
    },
    {
        "$unwind": "$data"
    },
    {
        "$addFields": {
            "found": {
                $in: [
                    "$data.id",
                    "$details.id"
                ]
            }
        }
    },
    {
        "$addFields": {
            "details": {
                $cond: [{
                        $eq: [
                            true,
                            "$found"
                        ]
                    },
                    {
                        $first: {
                            $filter: {
                                input: "$details",
                                as: "data",
                                cond: {
                                    $eq: [
                                        "$$data.id",
                                        "$data.id"
                                    ]
                                }
                            }
                        }
                    },
                    "$data"
                ]
            }
        }
    },
    {
        "$sort": {
            "details.id": 1
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "user": {
                "$first": "$user"
            },
            details: {
                "$addToSet": "$details"
            }
        }
    }
])

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

When a user clicks on a list item, a class is added to change the background color of that particular item while simultaneously removing the class from other list items

add image description hereI'm attempting to apply a class to the list item in an unordered list when clicked, while simultaneously removing the same class from the other list items. I've tried using the JavaScript logic below, but I'm not a ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

Encrypting data using JavaScript and then decrypting it with Ruby

Looking to securely encrypt a string in a client-side JavaScript application and decrypt it on a Ruby on Rails Server. Interested in utilizing AES for encryption. What would be the most effective combination of scripts, libraries, or methods to achieve t ...

What are alternative methods to prevent a div from expanding in width from the right side other than using position absolute?

Looking to create a div element that only expands from the left side as content is added? <div id="sent_message" style='background-color: #2b89cc; color: white; font-family: Arial,Helvetica, sans-serif; margin-top: 10px; display: ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

I'm looking to establish a cross-domain call in Tampermonkey in order to retrieve the contents of a div element. Can

After spending a few days tinkering with this, I have yet to make progress in successfully extracting data using a tampermonkey script. The closest I came was when I used this code http://jsfiddle.net/peterbenoit/N7avm/, which loaded the webpage/data succe ...

Nest a Div inside another Div with a precise margin of 10 pixels

Recently, I attempted to create a fullscreen webpage like this one: https://i.sstatic.net/21KCr.png My goal was to have the color of each element change randomly every second. Here is the JavaScript code I implemented: <script> var tid = se ...

Have I accurately configured the unit test for my Nest.js project?

I've created a test for my Nest.js project. Can someone please review and confirm if this test is correct? This test is focused on the nest service file. Here is the code: tasks.service.ts async getTaskById(id: string): Promise<Task> { con ...

What is the process for decrypting the data that was encrypted using node-jose?

I am currently in the process of incorporating basic JOSE encryption and decryption functionalities by utilizing node-jose. This is my code implementation (using Node 8.2.1) const { JWE } = require('node-jose'); const jose = (publicKey, privat ...

I am having trouble with saving documents in my local database using Mongoose

My issue seems to be straightforward. I am able to use mongoose to save documents to my DB on mlab and view the data using Postman on get requests. However, when I switch to a local MongoDB instead of mlab and try to display the database collections in my ...

React's conditional statement is malfunctioning

I am attempting to display a specific form for review if the user meets the following criteria: 1. Logged in 2. Not an administrator 3. Not a moderator My code currently looks like this: <h2>Write a Review</h2> {errorResortReview &a ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...

Utilize animation effects in jQuery to make text slide upwards and smoothly transition to a new text

I am currently working on developing a website that requires dynamic data changes. To enhance user experience, I aim to display the information in an animated format where text gracefully transitions by moving up and being replaced by new content emerging ...

Tips for troubleshooting React issue (TypeError: Cannot read property 'showModel' of null)

Learn how to set the attribute showModel and give it a value of false: Main.js import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import Form from 'react-bootstrap/Form' import Button from 'react-b ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

Executing a Parent Page JavaScript Method from Within an iFrame

I have included an iFrame in my application. To illustrate, consider the following example: The main page contains <html> <head> <script src='jquery.js'></script> <script> function TestFunction() ...

Using a Function to Retrieve Styles in React Native for Android

My goal is to dynamically add views based on the data received from JSON. Each event should be represented with a different color: red or blue. The app will insert a view accordingly. class MainPage2 extends Component { constructor () { super() var s ...

What is the best way to extract value from a specific link using JavaScript?

I have a PHP script that retrieves data from a database: <?php while($trackResultRow = mysqli_fetch_assoc($trackResult)){?> <a onclick="remove()"><span class="glyphicon glyphicon-thumbs-down pull-right"></span></a> < ...

Issue with jQuery not retrieving clicked text values correctly

In my current project, I am using a PHP script to retrieve values from the database. The code snippet looks like this: <div class="col-md-4" > <?php $query = "SELECT * FROM product_categories"; $r ...