Open In App

How to Move MongoDB Document from one Collections to Another ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is an essential ODM (Object Data Modeling) library for MongoDB designed to work seamlessly with Node.js. It provides a structured way to define schemas, making it easier to interact with MongoDB collections.

In this guide, we will cover the installation of Mongoose, the setup of schemas for source and destination collections and the implementation of a process to move documents between these collections.

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 MongooseMongoose 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 module
const mongoose = require('mongoose');

// Importing models from model.js
const { Source, Destination } = require('./model');

// Connecting to database
mongoose.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 collection
Source.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 module
const mongoose = require('mongoose');

// Defining source schema
const sourceSchema = new mongoose.Schema({
    field_1: String,
    field_2: String
});

// Defining destination schema
const destinationSchema = new mongoose.Schema({
    field_1: String,
    field_2: String
});

// Creating model for both schemas
const Source = mongoose.model('source', sourceSchema);
const Destination = mongoose.model(
    'destination', destinationSchema);

// Exporting our modals
module.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

Conclusion

By following this guide, you have successfully installed Mongoose and set up a basic structure to move documents from one collection to another within a MongoDB database. The process demonstrated how to define schemas, create models, and perform data migration operations using Mongoose. This setup forms the foundation for more complex data manipulation tasks and application development in Node.js with MongoDB.


Next Article

Similar Reads