Generate a distinct MongoDb ObjectId and append it to every element in a preexisting Array

I need to assign a unique Object Id to each transaction Array Object in an existing document.

{
_id: ObjectId(6086d7e7e39add6a5220d0a5),
firstName: "John"
lastName: "Doe"
transactions: [
  {
    date: 2022-04-12T09:00:00.000+00:00
    amount: 286.56
    type: "deposit"
    method: "Bank transfer"
  },
  {
    date: 2022-04-15T09:00:00.000+00:00
    amount: 120.23
    type: "withdrawal"
    method: "cash"
  }]
}

My goal is for each transactions Object to have its own unique ObjectId, but the current query I am using assigns the same ObjectId to all objects:

collection.updateMany({}, [
  {
    $set: {
      transactions: {
        $map: {
          input: "$transactions",
          in: {
            $mergeObjects: ["$$this", { _id: new mongo.ObjectId() }],
          },
        },
      },
    },
  },
]);

I'm trying to figure out why I'm not getting unique ObjectIds for each object in the transactions array. Any insights?

Answer №1

When running the code new mongo.ObjectId(), it will generate one ID for all members of the driver.
For each member, you need to ensure that the JavaScript runs on the server side.

To enhance efficiency, consider substituting the new mongo.ObjectId() with the following script using $function which executes on the server:
In most cases, it is recommended to avoid using JavaScript, but there may not be an aggregate operator available to create ObjectIds.

An alternative approach would involve creating a $map function entirely in JavaScript with the help of $function.

* Note: Using $function requires MongoDB version 4.4 or higher.

{
  "$function": {
    "body": "function () {return new ObjectId();}",
    "args": [],
    "lang": "js"
  }
}

Answer №2

Modifying the _id field in a document is not allowed as it is tying to modify the main objectId. It's recommended to use a different name for your transaction_id field instead.

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

How should a request from express/connect middleware be properly terminated?

If I have middleware like the following; var express = require('express'); var app = express(); app.use(function (req, res, next) { var host = "example.com"; if (req.host !== host) { res.redirect(301, host + req.originalUrl); ...

Using auto-incrementing model ids in MongoDB instead of relying on Mongo's built-in ObjectID system

Recently, a decision was made by management to utilize userId for the users collection, postId for the posts collection, and topicId for the topics collection, rather than '_id' as the unique identifier for each collection. This change has led t ...

Reassemble the separated string while skipping over every other element in the array created by splitting it

Currently, I am working on the following URL: demo.example.in/posts/0ewsd/13213 My goal is to extract the hostname (demo.example.in) and the path (posts/0ewsd/13213) from this URL. urlHost = 'demo.example.in/posts/0ewsd/13213'; let urlHostName ...

Excessive Global Lock Percentage in MongoDB

Just recently started using MongoDB v2.4.8 and noticed that the global lock % is averaging around 80%, which seems quite high to me. The CPU usage is at about 120% on a 2-core, 2GB RAM, SSD VPS running Ubuntu 12.04 64bit. When checking with `iotop`, occasi ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

Retrieving JSON data from a form in a Node.js application

Situation : Here is the HTML code I am working with <form action="http://example.com/nodejs/endpoint" method="post" enctype="multipart/form-data"> <label> Select JSON file <input type="file" name="json"> ...

Creating a responsive contact form using Javascript

I have a question regarding making a contact form responsive with javascript. I am still new to JavaScript, but I consider myself at a mid-level proficiency with HTML and CSS. The issue I am facing is that I recently registered with a third-party contact ...

What is the best way to swap out the Nan values for other values within an array?

I've tried various methods and reviewed the provided source code but I am unable to retrieve the values from the array. If I exclude the int in the for loop, I get NaN values. When including the int statement, the value turns into 0.00 which doesn&apo ...

Performing Ajax requests according to the selected checkbox data

Hey, I'm just starting out with Jquery and Ajax and could use some help to solve my issue. Currently, I am populating checkboxes based on my model values and making an ajax call to get a list of countries for each selected value. Now, I want to chan ...

HTML & JavaScript: A guide to registering for events on a hosted webpage

I have been exploring the creation of modular stand-alone (serverless) websites that can be hosted on IPFS. One technique I am utilizing to achieve modularity is by dividing single webpages into multiple HTML files and merging them by embedding one within ...

Refine your MongoDB collections with multiple filtering options

My dataset looks like this: [ {"userId": "0000", "algorithm": "algo1", "status": "Running", "waitingTime": 0}, {"userId": "0001", "algorithm": &qu ...

Using Vuex and array.findIndex but unable to locate a matching element

I am encountering an issue with the array.findIndex method. Despite being certain that there is a match in the array I am searching through, findIndex consistently returns -1. let index = state.bag.findIndex((it) => { it.id === item.id console. ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

The hyperlink function is not operational in Gmail attachments

Using an anchor tag to navigate to a specific section within the same page works perfectly when the HTML file is on my local machine. However, when I attach the file in Gmail and open the attachment, it doesn't work. Why is this happening? How can I m ...

How to incorporate a phone number input with country code using HTML

Can anyone help me create a phone number input field with a country code included? I've tried a few methods but haven't had much success. Here is the code I've been working with: <div class="form-group "> <input class= ...

Clicking on the Form Submission Button to Trigger a Page Refresh

I am seeking advice on a solution to prevent the page from reloading when the Form Submit Button is clicked. Utilizing a jQuery click event, I have implemented AJAX to transfer form data to a PHP file for validation and database entry. The PHP script pro ...

Twilio's phone calls are programmed to end after just 2 minutes

For the past week, I've been dealing with a frustrating issue where calls are being automatically disconnected after 2 minutes of recording. Here is the TwiML code: <Response> <Say voice="woman" language="en">Hii Welcome to our App</Sa ...

In what way does the map assign the new value in this scenario?

I have an array named this.list and the goal is to iterate over its items and assign new values to them: this.list = this.list.map(item => { if (item.id === target.id) { item.dataX = parseFloat(target.getAttribute('data-x')) item.da ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Change CSS style sheets depending on the size of the viewport

I've tried to implement the method from CSS-Tricks that allows for changing stylesheets based on the viewport width using multiple .css files and jQuery. However, my code isn't functioning as expected. I've spent the past hour trying to figu ...