Querying MongoDB findAndModify: <<< locate and modify an object within an array in a document

Question :

I am attempting to locate an object within a document's array and make updates to it.

The syntax below provides me with the desired object, but I am unsure of how to update it. I attempted to use this query in findAndModify, but it seems that $elemMatch cannot be used in the findAndModify method.

  db.users.find({"username":"username"},{"array":{$elemMatch:{"name":"name"}}})

Example JSON I am trying to modify

[{
"_id": ObjectId("5501b8fb77382c23704543fd"),
"username": "ker",
"password": "ker",
"character": "pet",
"visits": [],
"pets": [{"name": "Jura", "kind": "dog", "age": "2"}, {"name": "Ala",  "kind": "dog", "age": "5"}]
}, {
"_id": ObjectId("5501b8fb77382c23704543fd"),
"username": "mer",
"password": "mer",
"character": "pet",
"visits": [],
"pets": [{"name": "Ita", "kind": "cat", "age": "6"}, {"name": "Esa", "kind": "cat", "age": "1"}]
 }]

Overview:

My goal is to locate a specific document within a collection, then pinpoint an object within the document's pets array and make updates to that object.

Therefore, my logic follows this pattern

 db.collection.findAndModify({query:{Find Document In Collection THEN in document's array(pets) find object}, update:{$set:{New Values For Object}}})

Answer №1

If you want to achieve a specific task, you can execute the following query:

//To update a particular document using findAndModify
db.collection.findAndModify({

    //Specify the criteria for finding the desired document
    query: { username: 'mer', pets: { $elemMatch: { name: 'Esa'}}},

    //Update only the elements matching the specified criteria in the array
    update: { $set: { 'pets.$.name': 'CHANGED'}}
});

By running this query, you will modify the information of the second document as shown below:

{
        "username" : "mer",
        "password" : "mer",
        "character" : "pet",
        "visits" : [ ],
        "pets" : [
                {
                        "name" : "Ita",
                        "kind" : "cat",
                        "age" : "6"
                },
                {
                        "name" : "CHANGED",
                        "kind" : "cat",
                        "age" : "1"
                }
        ]
}

To learn more about updating documents with the $ positional operator, refer to this documentation

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

Transitioning from Backbone to AngularJS - What challenges can be expected?

Currently I am deep into a large Backbone project (around 8000 lines of JavaScript, not counting external libraries) and I am contemplating making the switch to AngularJS. At the moment, a significant portion of my code deals with DOM manipulation, event ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Two Elements Linked Together

I'm facing an issue with my interconnected React components. Despite being separate entities, they appear to share some styling attributes which I find puzzling. The main problem lies in the footer component as it seems linked to another component, p ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

JQuery Array: How to Prepend Elements to the Beginning

In my scenario, there's an input box labelled #status and a submit button with the class .btn. The requirement is simple: when something is typed into the input field and the button is pressed, I want that text to be added at the beginning of an array ...

Pass data in JSON format from Laravel controller to AngularJS

When working with Laravel, I successfully converted data in MySQL to JSON for use in AngularJS. However, I am now unsure of how to effectively utilize these values in AngularJS. Can anyone offer assistance? View output data (hide each value) Controller ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Steer clear of changing props directly in VueJS to prevent unintended

I am working with a component that has props, and I need to change the value from false to true. However, I encountered a message in the Chrome console advising against mutating a prop directly because it will be overwritten whenever the parent component r ...

Unexpected outcome from querying an element within an array located in an object in a mongoose schema

Presently, I am facing an issue with a mongoose schema structure. It appears as follows: { "_id" : ObjectId("some_id"), "repDet" : { "devIDs" : [ "dev1_B37", "dev2_B38", "dev3_B26" ], ...

Detecting collisions using CSS animation

I'm currently working on a unique "game" project. Check out the code snippet here: jsfiddle function update() { coyote.applyForce(gravity); coyote.edges(); coyote.update(); cactus.update(); if (coyote.intersects(cactus)){ alert("colisio ...

Is there a way to effectively transfer both Vertex and Face normals to a Three.js shader?

It seems that the THREE.Geometry methods, .computeFaceNormals() & .computeVertexNormals(), assign values to a built-in attribute array called "normal." If I want to utilize both vertex- & face-normals in one shader, I need to: Calculate face-normals ...

Combining the Powers of Express.js and Kue.js

Currently, I am working on a personal project that involves processing tasks in the background. To achieve this, I need to establish communication between my Express and Kue frameworks. Here is a brief overview of my setup: My Express.js application forks ...

What is the best way to determine if an array contains values similar to a specified string?

Currently engrossed in a project that involves the following: Gathering the most common phrases comprised of 2 to 5 words from a vast body of text (all going well) Creating an array with $phrase => $occurrences My next step is to take each value from ...

NodeJS tutorial on obtaining the Instagram username and access token

How do I retrieve the username and access token after a user logs in using Instagram-passport for my app login? I'm having trouble accessing the 'profile' in the middleware section. //serialize user in the session passport.serializeUser(fun ...

A guide to using select2.js to activate a selection based on a data attribute

I'm faced with the following html snippet: <div class='multiWrapper'> <select id="multi" class="js-dropdown-from-code"> <optgroup class='def-cursor' label='Code' data-city ...

Find the total number of records in fnClick: (datatables.net)

I am struggling with some code where I need to retrieve the total number of records. I posted about it on the datatables.net forum but unfortunately, no one was able to help me... tableTools: { "sSwfPath": window.STATIC_BASE + "scripts/datatable/s ...

retrieve data from a multidimensional array

I am working with an array: array(5) { [0]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [1]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [2]=> array(2) { [0]=> str ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

Stop the annoying page flicker in Next.js 12 by implementing a custom dark mode using Tailwind CSS classes

Is there a way to prevent the page flash when implementing dark mode in Tailwind CSS using classes in Next.js v12 without relying on third-party packages like next-themes? I have explored different solutions: This StackOverflow Q&A How to fix dark mo ...

Exploring Angular testing by using mock services to simulate the behavior of other services

I am familiar with how to mock a function call to a service. However, I am facing a scenario where my MainService acts as a wrapper for multiple other services. export class MainService { constructor( public service1: Service1, public service2 ...