What is the best way to eliminate specific elements from an array of objects in MongoDB aggregate based on a condition?

I have a database of documents called ChatRooms stored in MongoDB with the following structure:

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-02T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

My goal is to filter the messages array within an aggregate pipeline so that I only get one entry for each unique userId. The desired result should look like this (or something similar where the array does not contain duplicate entries for the same user id):

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

Is there a way to achieve this? Any assistance would be greatly appreciated.

Answer №1

There are numerous methods to accomplish this task, but here is an illustration of how you can do it by utilizing the $reduce operator:

db.collection.aggregate([
  {
    $addFields: {
      messages: {
        $reduce: {
          input: "$messages",
          initialValue: [],
          in: {
            $cond: [
              {
                $in: [
                  "$$this.user",
                  "$$value.user"
                ]
              },
              "$$value",
              {
                "$concatArrays": [
                  "$$value",
                  [
                    "$$this"
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Mongo 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

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

Tips on extracting code differences from code inspector

Utilizing the Chrome code inspector is extremely valuable, but I often find it challenging to track the modifications made to CSS and HTML live. This becomes particularly cumbersome when there are multiple tags being modified. Are there any Chromium exten ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

Using Ajax to fetch project data from an API

Currently immersed in a personal coding project, I'm struggling to troubleshoot my code. Essentially, I need to retrieve data from an API and display it on my HTML page. The data type is "jsonp" due to CORS errors that required this workaround for de ...

What is the best way to add up the attributes of objects within an array and save the total to the main

I have a collection of objects, illustrated here: var obj = { "ABC" : { "name" : "ABC", "budget" : 0, "expense" : 0, "ledgers" : [{ "Actual1920": 10, "Budget1920": 20, }, { "Actual1920": 10, ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

I am confused by the combined output of the Array method and join function in JavaScript

In my JavaScript code, I declared the myArr variable in the following way: var myArr= Array(3); Upon logging the value of myArr, I received the output: [undefined × 3] Next, I utilized the JavaScript join function with the code snippet: myArr.join(&a ...

Struggling to send a post request from an ejs file to the express server with data, yet finding that req.body is coming back as

Incorporating jquery ajax to send a post request to the server is part of my current project. The data being sent will be stored in the database and the structure of the post object is outlined within the script of my ejs file. <script> const ...

Is there a way to efficiently eliminate the button label from my dataset without causing any disruptions to my chart

I am looking to remove a specific label from my chart, but whenever I try to do so, it impacts the entire functionality. var ctx = document.getElementById("CountryChart");<br> var myChart = new Chart(ctx, {<br><br> type: 'bar&ap ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

Retrieve the route.js directory using Node.js

My server.js file is located in the directory: /dir1. To start the server, I use the command node server.js. In the directory /dir1/app/, I have my file named routes.js. I am trying to find out the directory path of the server.js file. However, I am unc ...

The jQuery framework is causing AJAX/API data to be duplicated in the

I've been encountering a common issue for which I can't seem to find a straightforward solution. My current challenge involves using an API to fetch JSON data through an AJAX call. Upon receiving the data, it appears twice in both the console an ...

Tips for including a variable in formData and the steps for implementing it in an ajax procedure

<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden> javascript code var clicked; $('#btnplusa').click(function(){ clicked = 'a'; $('#inpfile').click ...

I am currently studying react.js and struggling to comprehend how the deployment process for a react app functions

Will the server only serve the index.html file or is there a way for the client to run that html file as it's not a regular html file? Do I need a backend node to make it work? I'm having trouble understanding the entire process. Normally, a cli ...

NodeJs Express authentication with passport-jwt returning incorrect user data from token

I recently implemented an authentication API on my Node.js server, utilizing Passportjs as my middleware and passport-jwt as my strategy. Here is a snippet from my passport.js file let JwtStrategy = require("passport-jwt").Strategy, ExtractJwt = require ...

Step-by-step guide on deploying an Angular and Express project to Google App Engine

I am in the process of deploying my app to Google App Engine. I have already set up App Engine and installed gcloud on my local machine. While I have been successful in deploying some projects, I have only done so for Angular applications. My goal now is ...

Dynamically hiding elements within tabs using jQuery

Previously, I created a functionality for handling a single set of tabs. However, as the application has expanded, this functionality is no longer sufficient to accommodate multiple sets of tabs. The initial function looked like this: var iconTabs = func ...