How to move MongoDB document from one collections to another ? - GeeksforGeeks

24 May, 2021
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:
model.js: It contains schemas for the source collection and destination collection and exports models of both the schemas.
index.js: It contains code for moving a document from the source schema to destination schema.
index.js
// Requiring moduleconst mongoose = require('mongoose');  // Importing models from model.jsconst { Source, Destination } = require('./model');  // Connecting to databasemongoose.connect('mongodb://localhost:27017/geeksforgeeks',    {        useNewUrlParser: true,        useUnifiedTopology: true,        useFindAndModify: false,        useCreateIndex: true    });  // Finding a doc in the source collection by any // field and moving it to the destination collectionSource.findOne({ field_2: "Nodejs" })    .then(doc => {        console.log(doc);          // Inserting the doc in destination collection        Destination.insertMany([doc])            .then(d => {                console.log("Saved Successfully");            })            .catch(error => {                console.log(error);            })          // Removing doc from the source collection        Source.deleteOne({ field_2: doc.field_2 })            .then(d => {                console.log("Removed succesfully")            })            .catch(error => {                console.log(error);            });    })    .catch(error => {        console.log(error);})
model.js
// Requiring moduleconst mongoose = require('mongoose');  // Defining source schemaconst sourceSchema = new mongoose.Schema({    field_1: String,    field_2: String});  // Defining destination schemaconst destinationSchema = new mongoose.Schema({    field_1: String,    field_2: String});  // Creating model for both schemasconst Source = mongoose.model('source', sourceSchema);const Destination = mongoose.model(    'destination', destinationSchema);  // Exporting our modalsmodule.exports = {    Source, Destination}
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
MongoDB-method
Node.js-Methods
NodeJS-Questions
Picked
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method