如何将一个Mongo数据库中的记录插入另一个数据库?
您可以使用use命令从一个数据库切换到另一个数据库。在这里,我们使用“测试”数据库中的集合。让我们将该集合插入名为“sample”的另一个数据库中。
为了进一步理解,让我们使用文档创建一个集合。使用文档创建集合的查询如下-
> db.insertOneRecordDemo.insertOne({"UserName":"Larry","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534de16f542d757e2b452")
}
> db.insertOneRecordDemo.insertOne({"UserName":"Chris","UserAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534e816f542d757e2b453")
}
> db.insertOneRecordDemo.insertOne({"UserName":"David","UserAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534f116f542d757e2b454")
}在find()method的帮助下显示集合中的所有文档。查询如下-
> db.insertOneRecordDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c9534de16f542d757e2b452"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserName" : "Chris",
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"UserName" : "David",
"UserAge" : 25
}这是将记录从一个MongoDB数据库插入另一个数据库的查询-
> var AllDocumentsFromSourceCollection = db.insertOneRecordDemo.find();
> use sample;
switched to db sample
> AllDocumentsFromSourceCollection.forEach(function(allRecords){ db.getAllRecordsFromSourceCollectionDemo.insert(allRecords) });检查记录是否已插入。查询如下-
> db.getAllRecordsFromSourceCollectionDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c9534de16f542d757e2b452"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserName" : "Chris",
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"UserName" : "David",
"UserAge" : 25
}现在,您可以检查样本数据库中是否存在集合名称。查询如下-
> show collections;
以下是输出-
arraySizeErrorDemo basicInformationDemo copyThisCollectionToSampleDatabaseDemo deleteAllRecordsDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation documentWithAParticularFieldValueDemo employee findListOfIdsDemo findSubstring getAllRecordsFromSourceCollectionDemo getElementWithMaxIdDemo internalArraySizeDemo largestDocumentDemo makingStudentInformationClone oppositeAddToSetDemo prettyDemo returnOnlyUniqueValuesDemo selectWhereInDemo sourceCollection studentInformation sumOfValueDemo truncateDemo updateInformation userInformation
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短