Open In App

How to move MongoDB document from one collections to another ?

The following approach covers move MongoDB documents from one collection to another. With the help of mongoose, we will move a MongoDB document from one collection to another. Make sure that in the schema of both the collections all the fields are the same.

Install mongoose:



Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Now you can import the mongoose module in your file using:



const mongoose = require('mongoose');

Database: We already have documents in our Source and Destination collection before moving as shown below:

Source Collection before moving: Our source collection before the movement will look like this.

Source collection before moving

Destination Collection before moving: Our destination collection before the movement will look like this.

Destination collection before moving

Implementation:

Create a folder in which you can add two files model.js and index.js which are shown below:

index.js
 
model.js
 

Run index.js using the command: 

node index.js

Output:

Output in the console after executing index.js

Source Collection after moving: Our source collection after the movement will look like this.

Source Collection after moving

Destination Collection after moving: Our destination collection after the movement will look like this.

Destination Collection after moving

Article Tags :