如何将 MongoDB 文档从一个集合移动到另一个集合?
以下方法涵盖将 MongoDB 文档从一个集合移动到另一个集合。在mongoose的帮助下,我们将 MongoDB 文档从一个集合移动到另一个集合。确保在两个集合的架构中所有字段都相同。
安装mongoose:
第 1 步:您可以访问链接 Install mongoose来安装mongoose模块。您可以使用此命令安装此软件包。
npm install mongoose
第 2 步:现在您可以使用以下命令在文件中导入mongoose模块:
const mongoose = require('mongoose');
数据库:在移动之前,我们的 Source 和 Destination 集合中已经有文档,如下所示:
移动前的源集合:我们移动前的源集合将如下所示。
移动前的目的地集合:我们移动之前的目的地集合将如下所示。
执行:
创建一个文件夹,您可以在其中添加两个文件model.js和index.js ,如下所示:
- model.js:它包含源集合和目标集合的模式,并导出两个模式的模型。
- index.js:它包含用于将文档从源模式移动到目标模式的代码。
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
}
模型.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
}
使用以下命令运行index.js :
node index.js
输出:
移动后的源集合:我们移动后的源集合是这样的。
移动后的目的地集合:我们移动后的目的地集合将如下所示。