What is the process for removing a nested Mongo object located 2 arrays deep when its position is unknown?

In the given data below, I am looking to remove a specific 'answers' object nested within the Doc without knowing the index of the question or answer. The text of the answer that needs deletion is available, but not the exact location in the arrays.

For instance, if the question text I need to pinpoint is "This is a question." and the answer to be removed is "Answer One", how can this task be accomplished?

Here's an example of the MongoDB Doc: (Quizzes contain Questions; Questions consist of Answers)

{
    name: "Sample Quiz",
    categories: [
      { name: "testcategory1", description: "this is a test category" }
      ,{ name: "categoryTWO", description: "the second category" }
    ],

    questions: [

      { text: "This is a question."
        ,answers: [
          {text: "Answer One", affected_categories: "testcategory1"}
          ,{text: "Answer Two", affected_categories: "testcategory1"}
          ,{text: "Answer Three", affected_categories: "categoryTWO"}
        ]
      }

      ,{ text: "This is the second question."
        ,answers: [
          {text: "Mepho One", affected_categories: "testcategory1"}
          ,{text: "Answer Toodlydoo", affected_categories: "testcategory1"}
          ,{text: "Lehmen Sumtin", affected_categories: "categoryTWO"}
        ]
      }
    ],
  }

Deleting an item nested one level down (i.e., a question) was achieved using a query like:

    Quizzes.update(
      { _id: quizID, 'questions.text': questionText },
      { $pull: { questions: {text: questionText }}}
    );

(referenced here: http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations, under the section titled "Update an Element without Specifying Its Position")

An attempt was made to extend this method as follows:

Quizzes.update(
  { _id: quizID, 'answers.text': answerText },
  { $pull: { questions: {text: questionText {answers: {text: answerText }}}}}
);

However, the above approach did not yield successful results.

If you have any suggestions or solutions, please feel free to share them. Your assistance would be greatly valued.

Answer №1

To efficiently remove a specific answer, utilize the positional operator in conjunction with the $pull condition:

> db.quizzes.update(
      {_id:<quizID>, "questions.text":"This is the second question."}, 
      {$pull:{ "questions.$.answers":{"text":"Answer Toodlydoo"}}}
);

This code snippet effectively eliminates the designated answer from the specified question.

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

Customizing Your Google Maps Experience

I've encountered an issue with this code that's causing it to break when I attempt to apply stylers for customizing the colors of my Google Map. Can someone please help steer me in the right direction? What am I missing here? function initialize ...

What is the method for dividing a string (object) to 'preserve' in a fresh piece?

Upon receiving the following JSON file: var data = [ { "id":"1", "yMonth":"201901", }, { "id":"2", "yMonth":"201902", }, { "id":"3", "yMonth":"201802", }, { "id":"4 ...

Activate and focus on the text input field with a checkbox using AngularJS

Currently, I have a Bootstrap 3 input field with some prepended content along with a checkbox. My goal is to have the input field disabled until the checkbox is checked, and when it is checked, I not only want to enable the field but also set the focus on ...

Looking for a way to automatically load an aspx page when the browser is closing

Hey there, I'm struggling to load an aspx page when the browser is closed. I thought I had the code right, but it's not working. Can someone please lend a hand? Thanks! var clicked = false; function CheckBrowser() { ...

Surprising outcome caused by introducing a service dependency within another service in Angular 6

In my current project, I am facing an issue with ngrx-store and Angular 6. Unfortunately, I cannot replicate the problem on the stackblitz, so I will explain it here. I have a Service1 being used in the component, as well as a Service2 that is used within ...

I am encountering unexpected exponential values when using SVG.js group, even though I have stored the values as strings within the group

Utilizing SVG.js to store a numeric value as a String within a group (specified attribute). How can one retrieve the value as a string instead of an exponential numeric value? Despite converting the value to a String before adding it to the group, upon r ...

Updating the names of keys within an object that includes nested child objects

I am looking to update the keys in an object that contains nested objects with similar structures. Initially, my object looks like this: objs = { "one":{ "title":"bla", "amount":5, "children":[ { "title":"bla", ...

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

I kindly request your assistance in resolving the issues with the append() and empty

Here is some code I've been working on: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ ...

Having difficulty making changes to specific category fields in Magento 1.6

I've encountered an issue when trying to save specific fields in certain categories while editing them in Magento 1.6. The problem arises when attempting to edit the following fields within these categories: america/mini packages - description ameri ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

call a custom form submission using jquery first, followed by a regular form submission

Is it possible to attach a submit() handler to a form in order to execute an ajax request, and then have the form submit itself normally once the request is complete? Using $('#myForm').submit() seems to just result in the same function being cal ...

Sending files correctly using Node.js

Here is a simple middleware to consider: (req, res, next) => { const stream = fs.createReadStream(req.filePath) await new Promise((resolve, reject) => stream .on('error', reject) .on('end', resolve) .pipe(res ...

Delete a Woocommerce item from the shopping cart using ajax/fetch technology

My issue lies with the removal of products from the cart in Woocommerce, specifically involving WC_Cart::remove_cart_item. The error messages I am encountering are: POST http://localhost:3000/esport/wp-admin/admin-ajax.php [HTTP/1.1 500 Internal Server Err ...

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...

Vue - Display components next to sidebar

Having an issue with the vue-sidebar-menu. The sidebar is appearing over the components instead of beside them. Here is a screenshot of the problem: https://i.sstatic.net/cVgI6.jpg <template> <div id="app"> <sidebar-menu :menu="menu" ...

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...

Attempting to retrieve individual records from a MongoDB collection

Our collection features a basic versioning system with a unique field (pageId) serving as the primary identifier. All subsequent versions of a page share the same pageId, streamlining the process of retrieving all versions of a specific page. How can I ex ...