Adding new data to MongoDB alongside a corresponding key-value pair

I need to locate a specific object within an array, then insert additional data next to the matching key/value pair. Here is a sample scenario:

profile = [
   {
      data: 'value',
      array: [
         'one',
         'three'
      ]
   }
]

var i = 0;
var selector = 0;
_.each(profile, function(elem) {
    if (elem.data === 'value') {
        selector = i;
    }
    i++
}
profile[selector].array.push('two');

While this method works for adding to an array of objects/arrays, I'm looking for a way to achieve the same result using Meteor MongoDB. Is there a selector that allows me to pinpoint the correct array (based on a matching key/value pair) and then add new elements to the adjacent "array"?

Answer №1

If you have stored an object with a specific structure in mongodb, such as the following:

{
    profile : [
        {
            data: 'value',
            array: [
                'one',
                'three'
            ]
        }
    ]
}

You can utilize the following script in mongodb shell:

db.yourCollection.update(
    {"profile.data":"value"},
    {"$push":
        {
            "profile.$.array":"two"
        }
    }
);

This query locates the record where the profile's data property is set to "value" and appends "two" to the array property.

For more information, check out this resource: Mongodb $push in nested array

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

Is there a way to trigger this function with a button click event in Javascript, XSLT, XML, and HTML?

I need assistance with creating a webpage for my XML/XSL project that utilizes buttons to display country information when clicked. I initially achieved something similar using a dropdown list, but encountered issues when trying to implement buttons instea ...

Create a series of vertical lines using jQuery

I'm dealing with a JSON data set that I want to use to generate a grid. In addition to the grid, I also need to display vertical lines above it based on certain values: var arr = []; arr= [ {"Measure":"Air Pollution","Rank":"1","Value":"15.5"}, ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

Optimizing rest service calls with $resource

I am currently learning about the $resource to utilize RESTful Web Services. For my first attempt, I created a factory like this : 'use strict'; angular.module('BalrogApp').factory('Req', ['$resource', function($r ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Prioritize loading CMS content before mounting the React component

I am facing a challenge with importing my post from ButterCMS to React due to the async issue. import React, { useState } from "react" import Butter from "buttercms" import gradient from "../../images/TealLove.jpg" export default () => { const butt ...

Retrieve information from the database when the tab key is activated

Hey guys! I need some help with my project. I'm using jquery, ajax, and php to pull data from a database. My goal is to have the data automatically filled in a textarea when a user inputs a product code and presses the TAB key. I'm still new to a ...

Failover in MongoDB Java Driver for Replica Sets

Currently, I am managing a MonogDB replica set consisting of 2 members and an arbiter. However, when the primary node fails and MongoDB selects a new primary, data loss is occurring. I suspect this issue can be addressed at the Java driver level. I would ...

Unable to connect to React Node Socket.IO application from any source other than localhost using IPv4 and NGROK

I recently followed a tutorial on creating a simple React app/Node with Socket.IO. The tutorial worked perfectly, so I decided to test it with two other devices: One PC on the same wifi network (via IPv4 - 192.168.1.8:3000) A mobile device using Ngrok tun ...

Is there a way to exclude an entire folder from being processed in Next.js application?

When the "output" in nextConfig is set to "export", an error occurs in the app/api folder during the build process on the 13th. In my project, I require different build types based on environment variables. Is there a way to exclude the "api" folder from ...

What could be the reason for the callback not being triggered while retrieving all data from MongoDB?

After upgrading my machine to Node.js version 7.5.0 from version 4, I encountered issues with one of the applications that previously worked. The problem can be demonstrated through the following code: var connectionString = 'mongodb://127.0.0.1:2701 ...

Issue encountered during the process of importing Excel information utilizing the xlsx library

Currently, I am attempting to incorporate excel data into my angular application using the following library: xlsx However, upon downloading the project and attempting to run it locally, I encountered an error when trying to upload the excel file: Uncau ...

The Jquery .on Listener fails to attach a click listener to newly added elements

I'm experiencing an issue where the Jquery .on method is attaching the listener to the first button created when the page loads. However, when a new button is dynamically created by clicking on the previous one, the new button does not have any listen ...

Vue.js HTML not refreshing after axios request changes object property

Issue with Vue.js not updating HTML after axios GET request. Here's the structure: <span @click="tryResponse"> Data_object: {{ data_object }} <br> Data_object.serial: {{ data_object.serial }} <br> </span> Data ...

Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3. I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it ...

Update MYSQL table values using AJAX and jQuery, then dynamically refresh the updated values on the web page

Hey there! I am fairly new to utilizing ajax and encountering some difficulty with a fundamental concept. In my MySQL table called "users," I have various user information stored, including the balance they pledge to donate. My goal is to create a div elem ...

Adjusting Bootstrap 3 button group widths dynamically with ng-repeat

While utilizing a static method to display all radio buttons, everything works smoothly with 100% width. However, when I switch to a dynamic approach using ng-repeat, a line break issue arises. When not using ng-repeat: When using ng-repeat: Here's ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

Creating a TypeScript dynamic array that contains promises with varying return types

Is there anyone out there who can assist me in figuring out what's causing problems with this piece of code? I'm struggling to determine the correct type to use in that Promise.all call at the end. I attempted using Promise.all<Services[], Pul ...