After running the moving command, I wish to move all documents from database A to database B for backup and clean up some space in database A.
Result:
Database A:
I’ve written a small JS script to move the document from one collection to another collection in the same database:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb');
const SchemaA = new mongoose.Schema({
name: String,
apple: Number
});
const ModelA = mongoose.model('ModelA', SchemaA);
const SchemaB = new mongoose.Schema({
name: String,
apple: Number
});
const ModelB = mongoose.model('ModelB', SchemaB);
// function to move docs
async function moveDocuments() {
// get docs from ModelA
const docs = await ModelA.find().lean();
// insert into ModelB
await ModelB.create(docs);
// delete from ModelA
await ModelA.deleteMany({});
console.log('Documents moved!');
}
// call function
moveDocuments();
Please note that the code has been provided based on the sample data and the requirements mentioned above. The recommendation would be to perform thorough testing before using it in the production environment.