MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBでコレクションのクローンを作成しますか?


MongoDBでコレクションのクローンを作成するには、forEach()メソッドを使用できます。まず、ドキュメントを使用してコレクションを作成しましょう。

ドキュメントを使用してコレクションを作成するためのクエリは次のとおりです-

> db.studentInformation.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bc15780f10143d8431e21")
}
> db.studentInformation.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bc15e80f10143d8431e22")
}
> db.studentInformation.insertOne({"StudentName":"James"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8bc17380f10143d8431e23")
}

find()メソッドを使用して、コレクションのすべてのドキュメントを表示します。クエリは次のとおりです-

> db.studentInformation.find().pretty();

以下は出力です-

{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }

これがMongoDBでクローンを作成するためのクエリです-

> db.studentInformation.find().forEach( function(copyValue){db.makingStudentInformationClone.insert(copyValue)} );

MongoDBのクローンコレクションのドキュメントを確認してみましょう。クエリは次のとおりです-

> db.makingStudentInformationClone.find();

以下は出力です-

{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }

ここで、クローンを含むすべてのコレクションのリストを確認しましょう。クエリは次のとおりです-

> show collections;

以下は出力です-

copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
employee
getElementWithMaxIdDemo
internalArraySizeDemo
makingStudentInformationClone
prettyDemo
selectWhereInDemo
sourceCollection
studentInformation
updateInformation
userInformation

  1. MongoDBコレクションを配列値で並べ替えますか?

    MongoDBコレクションを配列値で並べ替えるには、$ sortとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo577.insertOne( ...    { ... ...       "student": { ...          "details": [ ...             { ...   &

  2. _idのMongoDBコレクションを更新していますか?

    _idを更新するには、MongoDBで$setを使用します。ドキュメントを使用してコレクションを作成しましょう- db.demo741.insertOne({SubjectName:"MySQL"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ead718657bb72a10bcf0672") } > db.demo741.insertOne({SubjectName:"C"}