如何将一个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 红包祝福语简短10字
18 周六早晨祝福语简短