确保 MongoDB 实例已正确配置并且已启动。
使用以下代码示例,将本地 MongoDB 数据库中的文档复制到 MongoDB Atlas。
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mylocaldb';
// Create a new MongoClient
const client = new MongoClient(url);
// Connect to the server
client.connect(function(err) {
if (err) {
console.log(err);
}
console.log("Connected successfully to server");
const localdb = client.db(dbName);
const atlasdb = client.db('myAtlasdb');
// Get a collection from localdb
const collection = localdb.collection('myCollection');
// Find all documents in the collection
collection.find({}).toArray(function(err, docs) {
if (err) {
console.log(err);
}
console.log("Found the following records");
// Insert each document into atlasdb
docs.forEach((doc) => {
atlasdb.collection('myCollection').insertOne(doc, (err, result) => {
if (err) {
console.log(err);
}
console.log(result);
});
});
// Close the connection
client.close();
});
});