Remove an element from an array in every object it is found in

My MongoDB document 'Org_unit' is structured as follows:

{
    "_id": ObjectId("0894f016e6e2e073c19e051"),
    "allowedusers": [
        "admin",
        "Fred",
        "Bob",
        "Layneh"
    ],
    "name": "News management",
    "divisions": [
        {
            "allowedusers": [
                "admin",
                "Larry",
                "Bob",
                "Harry",
                "Fred"
            ],
            "_id": ObjectId("60894f016e6e2e073c19e052"),
            "name": "Finances",
            "credentials": [
                {
                    "_id": ObjectId("94f0944f016e6e2e2342cc"),
                    "name": "FNB - FA",
                    "userName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88edf0e9e5f8e4edc8ede5e9e1e4a6ebe7e5">[email protected]</a>",
                    "password": "examplePassword!@#"
                }
            ]
        },
        {
            "allowedusers": [
                "admin",
                "Larry",
                "Bob",
                "Harry",
                "Fred"
            ],
            "_id": ObjectId("60894f016e6e2e073c19e052"),
            "name": "Development",
            "credentials": [
                {
                    "_id": ObjectId("94f0944f016e6e2e2342cc"),
                    "name": "FNB - DEV",
                    "userName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5a475e524f535a7f5a525e5653115c5052">[email protected]</a>",
                    "password": "examplePassword!@#"
                }
            ]
        }
    ],
    "__v": 11
}

Hello everyone, this is my first post here. I'm having trouble accomplishing a task with my database and hoping for some assistance.

Purpose of the Task:

I need to remove "Fred" from the "allowedusers" array within each "division" object in the "divisions" array.

What I Have Attempted:

Despite being new to this field (just about a week in), I've made numerous attempts to solve this issue. The closest I got was with the following code snippet:

Org_unit.updateMany({name: "News management"}, { $pull: {'divisions': {'allowedusers': "Fred"}}},{ multi: true })

However, this code ended up deleting the entire division if "Fred" appeared in its "allowedusers" array.

Any guidance on how to correctly achieve this would be greatly appreciated. Thank you in advance!

PS: Since this is my first question posted, any feedback on how I can improve my questions in the future is welcome!

Answer №1

Demonstration - Explore here

Utilize $[] documentation

The $[] symbol highlights that the update operation will affect all elements in the specified array field.

db.collection.update({
  name: "News management"
},
{
  $pull: {
    "divisions.$[].allowedusers": "Fred"
  }
})

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

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

using conditional parameters in a mongoose aggregation

I've got this functional aggregation code for mongoose const AccountProduct = await AccountProductModel.aggregate([ { $match: { userID: userID } }, { $addFields: { ...

Can the 'Water Shader Animation' be altered to have a non-spherical shape?

http://codepen.io/Khangeldy/pen/gPJoxJ JS // setting up camera, scene, and renderer var scene, camera, renderer; scene = new THREE.Scene(); var fov = 75, aspect = window.innerWidth / window.innerHeight; camera = new THREE.PerspectiveCamera(fov, a ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Querying MongoDB using the Java API

Below is a snippet of my MongoDB document: user:{ _id:1, name:'xyz', age:12, mobile:21321312, transaction:[{ trans_id:1, prod:'a', purchasedAt:ISODate("2015-02-01"), }, { trans_id:2, prod:'b', purchasedAt:ISODate("2015-02-01" ...

Experiencing a websocket issue despite not incorporating websocket functionality in the code

Whenever I attempt to run npm run dev, I encounter a websocket error. I'm part of a team with WSL and Mac users, and the repository runs smoothly for everyone else except me. I'm puzzled as to why I'm the only one facing this issue while try ...

Insert a percentage sign into a right-aligned text box

I am trying to figure out how to permanently display a % symbol at the far right side of a textbox that shows a percentage. Can anyone help me with this? ...

Incorporating a fixed header title when creating a customizable table

I am working on creating a dynamic table with rows and columns based on JSON data. JSON: $scope.dataToShow=[ tableHeder=["First Name","Age"], { name:"rahim", age:23 }, ...

A JavaScript code snippet to format a phone number in the pattern xx-xxxxxx

Please help me create a JavaScript function that can determine if the text in a textbox is a number. If it's not a number, I would like the function to focus on the textbox and change the format to look like this (xx-xxxxxx) when numbers are typed in, ...

How to search a specific field in ui.bootstrap typeahead efficiently

I'm currently enhancing my ui.bootstrap typeahead with some exciting features, but I've come across a challenge that I need help with. To better illustrate the issue I'm facing, I have put together a small Plunker example: http://plnkr.co ...

Creating a Halo (external outline) for a circular sector in THREE.JS

I'm working on adding a halo (external black outline) to certain shapes in three.js. While I was able to achieve this easily with rectangles and circles, I am facing challenges with circular sectors (not full circles). Here is my current attempt: It ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

Discover the parent DOM element of a specified element using jQuery

When using jQuery, I am currently exploring methods to navigate through the DOM until it locates a specific selector. For instance: Consider this structure: <span data-type="contact" data-filter="4" id="buyer-lookup" class="uneditable-input contact-lo ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...

Having trouble with my initialData in react-query - any suggestions on how to fix it?

I encountered an issue while trying to implement code using initialData in React Query. The output does not display as expected, and the key is not visible in the react-query-dev-tool. View image here import { useQuery, useQueryClient } from 'react-qu ...

Generating an Audio element on the fly using Javascript

I am looking to dynamically generate an audio tag within the <div class="audio-player" id="song"></div> section. I require: <audio id="audio-player" controls="controls" src="media/Blue Browne.mp3" type="audio/mpeg"> to be placed insid ...

Methods for applying a style property to a div element with JavaScriptExecutor in Selenium utilizing C#

I have been attempting to change the style of a div element using JavascriptExecutor in C#, but so far, nothing has happened. IJavaScriptExecutor js = (IJavaScriptExecutor)driver; IWebElement element = driver.FindElement(By.XPath("//div[contains(@class, ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

How can we change a jQuery document click function to an inline onclick function?

Under certain circumstances, I have to refactor my click function into a standalone function and trigger it using inline onClick="myFunction();" This is my current code structure: $(document).on('click','.exBtn', function(){ var ex = ...

Decoding JSON data

How do I parse 2 JSON objects? When AJAX returns just one object, it appears correctly: Object {32 : "Joseph"} However, when it returns more than 2 objects, this is what I get: ResponseText: "{"users":{"32":"Joseph"}}{"users":{"48":"Joseph K."}}" I h ...