📅  最后修改于: 2023-12-03 15:38:44.148000             🧑  作者: Mango
在 MongoDB 中,可以使用以下步骤将文档从一个集合移动到另一个集合:
首先,需要使用连接字符串连接到 MongoDB 实例,例如:
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
// ...
});
使用 find()
方法查询需要移动的文档,并将结果存储在一个数组中。例如:
const sourceCollection = client.db('mydb').collection('source-collection');
const documents = await sourceCollection.find({}).toArray();
这将查询 source-collection
集合中的所有文档,并将它们存储在 documents
数组中。
使用 insertMany()
方法将文档插入目标集合,例如:
const targetCollection = client.db('mydb').collection('target-collection');
const result = await targetCollection.insertMany(documents);
这将把 documents
数组中的文档插入到 target-collection
集合中。
最后,使用 deleteMany()
方法从源集合中删除文档,例如:
const deleteResult = await sourceCollection.deleteMany({});
将删除 source-collection
集合中所有的文档。
完整代码如下:
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
(async () => {
await client.connect();
const sourceCollection = client.db('mydb').collection('source-collection');
const targetCollection = client.db('mydb').collection('target-collection');
const documents = await sourceCollection.find({}).toArray();
const result = await targetCollection.insertMany(documents);
const deleteResult = await sourceCollection.deleteMany({});
console.log(`Moved ${documents.length} documents from 'source-collection' to 'target-collection'.`);
console.log(`Inserted documents ids: ${result.insertedIds}`);
console.log(`Deleted ${deleteResult.deletedCount} documents from 'source-collection'.`);
await client.close();
})();
这将输出以下内容:
Moved 10 documents from 'source-collection' to 'target-collection'.
Inserted documents ids: [ ObjectId("..."), ObjectId("..."), ... ]
Deleted 10 documents from 'source-collection'.
以上就是将 MongoDB 文档从一个集合移动到另一个集合的方法。