Removing data from a subdocument in Mongodb

I've been encountering difficulties trying to remove a subdocument in mongoDb. Despite attempting methods like $update, $push, and $pull, I haven't had any success.

Here is the document in question:

db.users.findOne({"_id": ObjectId("545677a9e4b0e0ef9379993c")})
{
    "_class" : "com.xxx.xxx.server.da.User",
    "_id" : ObjectId("545677a9e4b0e0ef9379993c"),
    "bookSummaries" : [
        {
            "_id" : ObjectId("545677e7e4b0e0ef9379993d"),
            "isbn" : "2746969644"
            "title": "test title"
        },      
        {
            "_id" : ObjectId("546a522a44ae4f5e652fdca7"),           
            "loanSummaries" : [
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473992044aec466a619290c"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "5473997d44aec466a619290d"
                },
                {
                    "loanStatus" : "REQUESTED",
                    "loanId" : "547605a744ae0f0d558ae757"
                }
            ],
            "testArray" : [
                {
                    "title" : "Back to the future",
                    "id" : "test"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test2"
                },
                {
                    "title" : "Back to the future",
                    "id" : "test3"
                },
                "test ",
                "test ",
                "test 2",
                "test 2",
                {
                    "loanStatus" : "REQUESTED"
                }
            ],
            "title" : "Back to the future"
        }
    ]
}

My goal is to generate queries for the following tasks:

  1. Delete the entire "testArray" subdocument only within this specific subdocument
  2. Delete a particular loanSummary based on its loanId within this specific subdocument

If anyone could assist me in crafting these queries, it would be greatly appreciated. I have searched through various posts but have not found a solution that fits my problem exactly.

Thank you very much

Answer №1

Dealing with a similar issue, I encountered the need to eliminate a nested subarray. When handling the query, it is crucial to pinpoint the specific object for removal. In the update query, utilize the $ sign as an index to extract the desired object from the array.

var query = {
       "_id" : ObjectId(someUserId),
       "bookSummaries._id" : ObjectId(bookId),
       "bookSummaries.loanSummaries.loanId" : loanId
 };

var updateQuery = {
      "$pull" : {
          "bookSummaries.$.loanSummaries" : {
                 "loanId": loadId
          }
      }
}

Update

I executed these queries successfully in my shell. Remember to input the relevant ids.

var query = { "_id" : ObjectId("53b73b1108fe927c0e00007f"),  "bookSummaries._id" : ObjectId("53b73b1108fe927c0e00007f"), "bookSummaries.loanSummaries.loanId" : "53b73b1108fe927c0e00007f" }

var updateQuery = { "$pull" : { "bookSummaries.$.loanSummaries" : {  "loanId": "53b73b1108fe927c0e00007f"  } } }

Update 2

If you are aware of the index of the item/object to be removed, execute the following queries for achieving this.

Locate the document for editing

var query = {
   "_id" : ObjectId(someUserId),
};

Deselect the object to be eliminated

var update1 = {
  "$unset" : {
      "bookSummaries.1.loanSummaries.2" : 1
  }
}

Pull the object containing null value

var update2 = {
  "$pull" : {
      "bookSummaries.1.loanSummaries" : null
  }
}

To remove, utilize the same set of queries.

Locate the document for editing

var query = {
   "_id" : ObjectId(someUserId),
};

Deselect the object to be eliminated

var update1 = {
  "$unset" : {
      "bookSummaries.0.testArray" : 1
  }
} 

Answer №2

When faced with a similar task, I had to remove several subdocuments rather than just one. My approach involved using an array of IDs to achieve this:

User.findOneAndUpdate(
      { _id: userId },
      {
        $pull: { documentList: { _id: { $in: idArray } } },
      });

Answer №3

With MongoDB's capability to offer a complete JavaScript environment, you have the flexibility to easily modify the document and update the data in the database.

*Please note: If you are utilizing MongoDB in conjunction with PHP or Python, there are similar methods available for accomplishing the same tasks.

1. To remove the entire "testArray" subdocument for a specific index (1) within this particular subdocument:

db.users.find({"_id": ObjectId("545677a9e4b0e0ef9379993c")}).forEach(function (user) {
    delete user.bookSummaries[1].testArray;
    // Saving the modifications 
    db.users.save(user);
 });
  1. To eliminate a specific loanSummaries entry based on its loanId, such as id 5473992044aec466a619290c:

    db.users.find({"_id": ObjectId("545677a9e4b0e0ef9379993c")}).forEach(function (user) {
        var loanToDelete = "5473992044aec466a619290c";
        var loanIndexToDelete = -1;
    
        var i;
        for(i in user.bookSummaries[1].loanSummaries) {
            if(user.bookSummaries[1].loanSummaries[i].loanId === loanToDelete) {
                loanIndexToDelete = i;
                break;
            }
        }
    
        if (loanIndexToDelete > -1) {
          delete user.bookSummaries[1].loanSummaries[loanIndexToDelete];
        }
    
        // Saving the changes
        db.users.save(users);
    });
    

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

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

Ensuring that an added row remains at the bottom of a table composed of rows generated dynamically by utilizing the .detach() method

I need to ensure that the "subtot" row is always appended as the last row in the table. When dynamically adding rows, the "subtot" row appears as the last row the first time, but does not stay at the bottom when more rows are added. Even though I want the ...

Incorporate PHP form and display multiple results simultaneously on a webpage with automatic refreshing

I am currently in the process of designing a call management system for a radio station. The layout I have in mind involves having a form displayed in a div on the left side, and the results shown in another div on the right side. There are 6 phone lines a ...

A new date picker applied to a dynamically generated form field

I am utilizing the daterangerpicker from this Github link. My goal is to generate new input fields using JavaScript when a button is clicked. How can I ensure that the daterangepicker script functions correctly? I must admit, I am not well-versed in JavaSc ...

The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure. This particular file is my employeeController.js (function() { angular.module('employeeApp').controller('employeeController', employeeCont ...

Error: React.createElement function requires a valid type parameter

At first, I want to clarify that I am not using the regular extends React.Component, but rather ES6. The issue lies with my Layout component. I have imported it into my app.js file as import Layout from './components/Layout';. However, upon chec ...

Attempting to incorporate Google charts into a div using jQuery's load function

Trying to incorporate a basic Google chart using jQuery .load functionality to transfer the chart into another webpage with a specific containing DIV: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi">< ...

Searching for multiple white spaces in JavaScript to ensure that no empty data is transmitted and removing any excess spaces

I'm a little puzzled on how to tackle this issue. It seems like a common problem, but my search didn't yield any helpful results. I have an HTML textarea and input textbox that I want to validate in the following ways: Prevent users from enteri ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

Dramatist: Verifying DOM once printer dialogue appears

After opening the printer dialog option on a PDFjs page, I aim to make assertions on the DOM. What I intend to accomplish: Start by loading the page () Wait for the .page class divs to load (waitFor({ state: 'attached' }) Click on the Print but ...

Display a tooltip when the user hovers over the column name of a BootstrapVue table

I am currently working with a bootstrap-vue table that has the following structure; https://i.sstatic.net/bfS9u.png Below is the code for setting up the table; <template> <div> <b-table striped hover :items="items" :fields= ...

Create a dynamic select2 field based on the value selected in another dropdown menu

Starting with an initial dropdown where a value needs to be selected: <select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;"> <option value='' selected>Choose an Index</option> ...

What is the best way to transmit UTF-8 Arrow &#8594; from typescript to html and showcase it effectively?

When working with HTML, I often find myself creating a div with a tooltip that is connected to a function. Here's an example of what I typically use: <div *ngFor="let user of users"> <div class="myClass" [matToolt ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Retrieving Nearby Zip Codes using a JSON Rest API in AngularJS

Check out this accessible JSON formatted URL: Here's the code snippet I used to store the JSON data in a variable: var url = "http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=js ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

Acquiring the markers, however the latitude and longitude are both null - vue.js

I have been working on displaying markers on a map. When I fetched the data, everything seemed fine in Vue DevTools. The `this.markers` property also contains the data. However, to my surprise, the values for `lat` and `lng` inside the markers are showing ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Bring in numerous documents utilizing a glob pattern

Currently, I am in the process of developing a modular React application. However, I have encountered an issue where I am unable to dynamically import the routes for my app. Consider the following file structure: app ├── app.js └── modules ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...