如何在 MongoDB 中将集合从一个数据库复制到另一个数据库?
mongodbdatabasebig data analytics
MongoDB 中没有将集合从一个数据库复制到另一个数据库的命令。要实现此目的,请使用以下概念 −
db.yourCollectionName.find().forEach(function(yourVariableName){
db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName);
});
让我们在测试数据库中创建一个集合,并将其复制到另一个名为"sample"的数据库中。
为了理解上述语法,让我们创建一个包含文档的集合。创建包含文档的集合的查询如下 −
<test>
> use test
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":101,"UserName":"Larr
y"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77ad622386c62d05142a67")
}
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":102,"UserName":"Maxwell"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77ad6e2386c62d05142a68")
}
> db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":103,"UserName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77ad7c2386c62d05142a69")
}
使用 find() 方法显示集合中的所有文档。查询如下 −
> db.copyThisCollectionToSampleDatabaseDemo.find().pretty();
以下是输出 −
{
"_id" : ObjectId("5c77ad622386c62d05142a67"),
"User_Id" : 101,
"UserName" : "Larry"
}
{
"_id" : ObjectId("5c77ad6e2386c62d05142a68"),
"User_Id" : 102,
"UserName" : "Maxwell"
}
{
"_id" : ObjectId("5c77ad7c2386c62d05142a69"),
"User_Id" : 103,
"UserName" : "Robert"
}
让我们检查示例数据库是否有名为"copyThisCollectionToSampleDatabaseDemo"的集合。
查询如下 −
<sample>
> use sample; switched to db sample > show collections;
以下是输出 −
deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
因此,不存在名为"copyThisCollectionToSampleDatabaseDemo"的集合。
现在,我们将上述集合从测试数据库复制到示例数据库。查询语句如下:−
> use test;
switched to db test
> db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send){
db.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send); });
现在,让我们再次检查集合是否已成功复制到示例数据库中。
查询如下 −
> use sample; switched to db sample > show collections;
以下是输出 −
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
查看示例输出,集合"copyThisCollectionToSampleDatabaseDemo"存在于示例数据库中,也存在于测试数据库中。

