Combine two collections into a single collection in MongoDB using JavaScript

I have been attempting to merge two collections into a new collection while inserting the resulting data into the new collection.

Here is the code I am using for the merge:

db.users.aggregate(
  [{
    $lookup: {
      from: "posts",
      localField: "_id",
      foreignField: "_uid",
      as: "postsByUser"
    }
  }])

I am aware that this code returns a new collection/array. Now, I am trying to insert this new array into a new collection using this code:

db.postsByUsers.insert(db.users.aggregate(
  [{
    $lookup: {
      from: "posts",
      localField: "_id",
      foreignField: "_uid",
      as: "postsByUser"
    }
  }]))

However, the result I am getting in the "postsByUsers" collection is not what I expected. I am seeing additional fields like: _useReadCommands, _cursorid, _batchSize, etc. I am getting the information I need in the field called _batch but it is not as organized as I would like. I want it to be an array with objects inside it, including the postsByUser field at the end to provide all the necessary information. I have tried setting a variable usersPosts equal to the aggregation I performed and looping through each document using

db.postsByUsers.insert(usersPosts)
but nothing seems to happen:

usersPosts.forEach(function(doc){
  db.postsByUsers.insertOne(doc)
})

I did manage to obtain the desired result at one point, but I am unsure why. I have tried going back through the code by pressing the up key on the command line, but nothing has replicated the successful outcome. Any assistance is greatly appreciated. Thank you for taking the time to read this!

Answer №1

The $out aggregation pipeline stage in MongoDB allows you to store the result of an aggregation pipeline in a separate collection.

{ $out: 'newCollection' }

As of MongoDB 4.2, the $merge operator can also be used to merge result documents with existing ones, providing more flexibility.

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

Dealing with errors in Smart Query using Nuxt and Vue Apollo: How to navigate to specific error pages for 404, 400, or 500 errors and is it possible to catch

When utilizing Smart Query for redirection, how can we redirect to a 400 page? While working with Vue Apollo, I attempted the following: apollo: { queryName: { prefetch: true, query: wrongQuery, error(e ...

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Managing empty props in React applications

I am facing an issue where I need to display an image fetched from an API on app start, but when I try to render it in React, the application crashes with the error message: TypeError: Cannot read property 'icon' of undefined. Although the icon ...

Obtain the refined information from a UiGrid table

Is there a way to loop through the filtered rows in an uigrid? I am aware that we can get the filtered rows using the following code: var filteredData = $scope.gridApi.core.getVisibleRows($scope.gridApi.grid); However, I need to iterate through it and cr ...

Error: The cordovaLocalNotification plugin is attempting to read a property 'plugins' that is undefined, resulting in a TypeError

I am currently working on a hybrid application using the Ionic platform. I am trying to integrate Cordova local notification features, but I keep getting an error message saying "cannot read property 'plugins' of undefined." Below is my code. Can ...

Modify the appearance of an element within an array upon selection by comparing it with a separate array

In my code, there is an array called tagList that contains a list of objects. When one of these objects is clicked on, it gets added to another array named selectedTags. var selectedTags = []; export default class RegisterTags extends Component { con ...

Nextjs: where all roads lead back to the homepage

Having an issue in my app where all redirects keep leading back to the homepage. The problem seems to stem from my Navbar.js component, as shown below. Despite adding the required route in the Link tag for next-js, both client and server compilation is suc ...

Issues with Javascript functionality in Internet Explorer and Google Chrome

Hello everyone, I'm experiencing an issue with a thumb image link swapping out on hover. Oddly enough, it seems to work perfectly in Firefox and Safari, but it's not showing up on IE and Chrome. As I am relatively new to Javascript, I may be over ...

Execute a script upon page load

Is there a way to trigger a script tag <script> immediately upon the website loading? I've experimented with various codes, but haven't found one that meets my needs. ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Retrieve information in JSON format using AngularJS by fetching data from SQL through PHP

My objective is to retrieve data from a mySql database using PHP, convert it to JSON, and then display it through AngularJS. Although I have successfully completed the steps leading up to this point, I am facing issues with the final step. Below are the de ...

Adjusting the opacity of a div while scrolling

I've searched multiple pages, but haven't found a solution that works for me. I'm trying to make the text in my div gradually become more transparent as I scroll. Can anyone help with this? Here's my code: <script src = "/js/titleSc ...

Ways to determine the completion of the compilation process in Angular using the $compile service

Imagine having a popup directive that inherits a string template for the content it should display from the $scope. scope: { template: '=popInfo'//<div another directive></div> } This template string may even include another dire ...

Numerous entities in motion, each adorned with its own accompanying text

I have been experimenting with the interactive cubes and recently implemented a click function that directs to specific links. Now, I am interested in assigning distinct text to each cube as a material when rendered. Currently, I am using a single materi ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

How can I effectively send data from a view to a controller using AJAX in C# using Leaflet?

Every time I attempt to pass data from the view to the controller, I keep receiving an "alert request failed" message. I am uncertain of the datatype for leafletLats and leafletLngs, but they are both arrays derived from coord which is of type LatLng[]. ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

Explaining the structure of a nested object within a TypeScript declaration file

As I work on my project, I encounter the challenge of importing an object created by a dynamic function. The dynamic nature of the keys on this object poses a problem for the IDE, as it cannot determine what keys are present based on the provided config. T ...

Notify user before exiting the page if there is an unsaved form using TypeScript

I am working on a script that handles unsaved text inputs. Here is the code for the script: export class Unsave { public static unsave_check(): void { let unsaved = false; $(":input").change(function(){ unsaved = true; ...