如何将一条记录从一个 MongoDB 数据库插入到另一个数据库?
您可以使用 use 命令在数据库之间切换。在这里,我们正在使用 “test” 数据库中的集合。让我们将该集合插入到另一个名为 “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() 方法显示集合中的所有文档。查询如下所示:
> 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 }
现在您可以检查集合名称是否在 sample 数据库中存在。查询如下所示:
> 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
广告