Tips for storing a single document in two separate collections within the same MongoDB database

I am currently exploring nestjs and I am faced with a challenge. My goal is to retrieve a document from collection_1 and then store the same document into collection_2. I have tried using the $out aggregation, but found that I am only able to save one document in collection 2 at a time. Each time I attempt to save a second document, the first document disappears. I am seeking a solution to save every document from collection 1 into collection 2 without losing any data.

Here is the service code snippet:

async order(name){
    const list = await this.usersmodel.find({name: name}).exec()
    // return list
    try{
        if(list){
            const x = await this.usersmodel.aggregate([
                { $match: { name: name } },
                {$out:"payment"}
            ])
            return "Data successfully saved in the payment collection"
        }
    }
    catch(error){
        return(error.message)
    }
}

And here is the corresponding controller code:

@Post('orderdata')
async orderdata(@Body('name') name){
    return this.usersService.order(name)
}

Answer №1

To leverage the power of MongoDB 4.2+, consider using the $merge operator.

await this.usersmodel.aggregate([
    {
        $match: {
            name: name
        }
    },
    {
        $merge: "payment"
    }
])

The $merge operator provides additional options for updating existing documents as needed.

For users on older versions of MongoDB, achieving this task in a single action is not possible. Instead, you will need to first query collection1 and then insert into collection2 separately.

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

execute the function based on the given ID

I've been attempting to dynamically add content using a function. My goal is for the content with the same anchor ID as the clicked anchor to be added, but it seems like nothing is happening. Is there a more effective approach to achieve this? $(&a ...

What is the process for including an "everything" alternative on a dropdown menu?

Need assistance with my dropdown component that filters a list based on 'state' data. Below is the HTML code for the dropdown: <section class="select-wrapper {{wrapperClass}}" [ngClass]="{'expanded': toggle}" (click)="toggleSelect($ ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

MongoDB Issue: Subdocuments not returning with multiple populate queries

I have been trying to retrieve a complete data object of both the documents and subdocuments, but all I am getting is the documents along with the ObjectID of the subdocuments. I have attempted multiple populate statements, but nothing seems to be working. ...

How can I optimize my queries for maximum efficiency in MongoDB?

Within my extensive MongoDB collection consisting of over 4 million documents, I attempted to retrieve documents using two different approaches. db.getCollection(collectionName).find(new Document("lang", lang)) .skip(skip).limit(limit).sort(new Do ...

Show complete items in Vue.js

Issue at hand: I am in need of displaying and potentially changing JSON data. My goal is to present it in a directory tree format. The structure of the object is unknown, it could be something like this: "buttons": { "login": "LOGIN", "register": ...

Messy code appeared when sending an AJAX post to JBoss EAP 7 without using encodeURIComponent

Initially, the project functions smoothly on tomcat using UTF-8 and jboss eap 6 with UTF-8 page encoding as well. Additionally, the jboss configuration includes: <servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="loc ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Confirm Submission Issue in HTML Form

During my testing of the blacklist confirmation dialog, I encountered an issue where clicking the OK button did not submit the form as expected. Instead, it seemed to be stuck in a loop where clicking the button had no effect and the dialog remained on scr ...

The justify-between utility in Tailwind is malfunctioning

Can someone help me figure out how to add justify-between between the hello and the user image & name? They are in different divs, but I've tried multiple ways without success. I'm fairly new to this, so any advice would be appreciated. This ...

Update the variable obtained from the user input and insert it into a new container depending on the input value

In reference to my previous inquiries, I refrain from adding more details to avoid confusion since it already received numerous responses. While I can successfully retrieve input from a text field with the ID 'test' and display it in the 'r ...

Is there a way to access the scrolling element on the current webpage?

When the route changes, I need to locate the element with scrolling functionality on the new page and scroll it to the top using window.scrollTo(0,0). How can I achieve this? Here is my current code snippet: if (process.client) { router.afterEach((to, ...

Create distinct 4-digit codes using a random and innovative method, without resorting to brute force techniques

I am working on developing an application that requires generating random and unique 4-digit codes. The range of possible codes is from 0000 to 9999, but each day the list is cleared, and I only need a few hundred new codes per day. This means it's fe ...

Tips for effectively utilizing TypeORM transactions

I'm encountering an issue with transactions in TypeORM. Here's a snippet of the code causing me trouble: const someFunction = async () => { try { await this.entityManager.transaction(async (manager) => { //some opera ...

While attempting to use $scope.$apply() in Angular, I encountered a bug that

I have set up a specific example in a jsbin: http://jsbin.com/deqerelita/1/ Situation The concept is quite straightforward. You click a button, the controller adds to the model, and the view updates accordingly with a hidden input type="file". After the v ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

What is the best way to ensure a textarea remains expanded when the parent element is in focus?

I have successfully implemented a textarea box that expands upon click and retracts when it loses focus. However, I am facing an issue where if the textbox is already in expanded form, I want it to stay expanded if the user clicks anywhere within the cont ...

Prevent automatic merging of JSON data with identical IDs

My AJAX call to a PHP select request is as follows: $.ajax({ type: "POST", url: "/renforts/_getIntervenantManager", data: { IDMission : IDMission, IDManager : IDManager }, dataType : 'json' ...

Encountering a 403 error when attempting to upload files to Google Cloud Storage (GCS) using Signed URLs

The main aim is to create a signed URL in the api/fileupload.js file for uploading the file to GCS. Then, retrieve the signed URL from the Nextjs server through the nextjs API at localhost://3000/api/fileupload. Finally, use the generated signed URL to upl ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...