Modify the values of items within an array based on their corresponding IDs within the array

Looking to update the object values of an array in a document, but first needing to find its ID. Here is the structure of the document:

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'unread'
       },
       {
         _id: ObjectId('2')
          status: 'unread'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}


The goal is to update the status of notifications under that user where the object ID matches those in the result array.

result = 
  [
  new ObjectId("1"),
  new ObjectId("2"),
  ]

This should produce the following result after the update:

{
_id: ObjectId('12312')
notifications: [
       {
         _id: ObjectId('1')
          status: 'read'
       },
       {
         _id: ObjectId('2')
          status: 'read'
       },
       {
         _id: ObjectId('3')
          status: 'unread'
       }
    ]
}

Here is the current progress made, but the desired outcome is not achieved yet:

  const updateUser = await User.updateMany({_id:idofuser, "notifications._id": { $in : result }},{
     $set: {
            "notifications.$.status": "read",
         }
   })

Answer №1

To loop through the elements in notifications and update them conditionally, you can utilize $map, $cond, and $mergeObjects.

db.collection.update({
  "_id": "12312"
},
[
  {
    "$set": {
      "notifications": {
        "$map": {
          "input": "$notifications",
          "as": "n",
          "in": {
            "$cond": {
              "if": {
                "$in": [
                  "$$n._id",
                  [
                    "1",
                    "2"
                  ]
                ]
              },
              "then": {
                "$mergeObjects": [
                  "$$n",
                  {
                    "status": "read"
                  }
                ]
              },
              "else": "$$n"
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Check out the Mongo Playground link for a live demonstration.

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

.NET Core ViewModel with IFormFile attribute causing AJAX Request to freeze

Users now have the option to upload images for a retail product within an Add/Edit Product modal. Product Modal ViewModel: public class ProductModalViewModel { public ProductModalViewModel() { Product = new ProductDTO(); Images = ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

In the world of JavaScript, one moment an array reference works perfectly on a single line, and the next moment a TypeError

I'm puzzled by the recurring TypeError: selected_tiles[count] is undefined error message I keep encountering when using console.log line. It seems to work fine in the preceding if statement, so why does it fail afterwards? //note that tiles are actu ...

Safari showing white flash upon setting background-image src using Intersection Observer?

I've done extensive research but I'm still struggling to solve this issue. It only seems to be happening on Safari (Mac & iOS), while everything works smoothly on Chrome, Firefox, Edge, and other browsers. UPDATE: The flickering problem also per ...

What are the steps for displaying multiple input fields using the onchange method?

$(document).on("change","#noofpack",function(){ count = $(this).val(); for(i=1;i<=count;i++){ $("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">'); ...

Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this: <p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom" required="true" requiredMessage="Please select ...

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...

Is there a way for me to connect to my Firebase Realtime Database using my Firebase Cloud Function?

My current challenge involves retrieving the list of users in my database when a specific field is updated. I aim to modify the scores of players based on the structure outlined below: The Realtime Database Schema: { "users": { &quo ...

A guide on understanding tab-formatted text in a textarea using JavaScript (Vuejs)

Trying to decipher a text that has been copied into a Word table, the formatting is very confusing. I am looking to extract the rows as objects in an array, with the columns serving as properties of each object. I would like to accomplish this using Vuejs ...

Transferring JSON data from JavaScript to ASP.NET

In my web app, the backend is built in ASP.net. The ajax call I'm using is a standard get request. $.ajax({ url: 'myurl/updatejson', contentType: "application/json; charset=utf-8", data: data, success: function (data) { ...

Syntax in Next.js for shallow routing

When working with next js, I want to update the route without refreshing the page. Currently, I am using the following syntax which I find cumbersome: Router.push( `/statistics?entityId=${id}&type=${entityType}&provider=${serviceProvider}`, ...

How can I clear a text box in Angular.js when the Google Autocomplete event is triggered?

Seeking assistance in AngularJS to clear the textbox value upon triggering the google map autocomplete event. Can anyone provide guidance? Here is the HTML code - <input ng-model="deployText" id="search_execute" class="form-control" type="text" place ...

Creating a stylish CSS button with split colors that run horizontally

Could you please provide some guidance on creating a button design similar to this one? I've made progress with the code shown below, but still need to make adjustments like changing the font. <!DOCTYPE html> <html> <head> <sty ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

Adjust the horizontal position of a text element using CSS

I am faced with a specific challenge where I need to center the text "test" within a text tag using only CSS, without being able to directly change the HTML. <text width="13.89" height="13.89" x="291.46999999999997" y="156.55" transform= ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

PHP Hourly Agenda, Cycling through time records stored in database

In my MySQL table called 'my_cal', I have a column named 'start_time' for specific events in the calendar. When adding items to the database, there are no overlapping events. Sometimes, there may not be an event scheduled for a particu ...

Ways to provide a unique backend experience for each frontend app by utilizing different databases for each connection

Is there a way to deploy my backend on a server and connect multiple frontend apps to it, each with its own database? I am using Node, express, mongoose, mongodb. The logic of the backend will remain the same, but I require different databases for each fro ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

Creating Irregular-shaped Array

As I work on a program to display a jagged array, I encountered some challenges. Initially, I tried using a foreach loop but it failed to print the array when the program was executed. Switching to a for loop resulted in a System.IndexOutOfRange exceptio ...