Programing

MongoDB에서 한 데이터베이스에서 다른 데이터베이스로 컬렉션을 복사하는 방법

lottogame 2020. 5. 1. 07:59
반응형

MongoDB에서 한 데이터베이스에서 다른 데이터베이스로 컬렉션을 복사하는 방법


이를 수행하는 간단한 방법이 있습니까?


현재 MongoDB에는이 작업을 수행하는 명령이 없습니다. 관련 기능 요청이 있는 JIRA 티켓을 참고하십시오 .

당신은 다음과 같은 것을 할 수 있습니다 :

db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_database>')['<collection_name>'].insert(d); });

이를 통해 두 데이터베이스가 작동하려면 동일한 mongod를 공유해야합니다.

이 외에도 한 데이터베이스에서 컬렉션의 mongodump를 수행 한 다음 컬렉션을 다른 데이터베이스로 mongorestore 할 수 있습니다.


가장 좋은 방법은 mongodump를 수행 한 다음 mongorestore를 수행하는 것입니다.

다음을 통해 컬렉션을 선택할 수 있습니다.

mongodump -d some_database -c some_collection

[선택적으로 덤프 ( zip some_database.zip some_database/* -r) 및 scp다른 곳을 압축하십시오. ]

그런 다음 복원하십시오.

mongorestore -d some_other_db -c some_or_other_collection dump/some_collection.bson

기존 데이터는 some_or_other_collection보존됩니다. 이렇게하면 한 데이터베이스에서 다른 데이터베이스로 컬렉션을 "추가"할 수 있습니다.

버전 2.4.3 이전에는 데이터를 복사 한 후 색인을 다시 추가해야합니다. 2.4.3부터이 프로세스는 자동으로 수행되며을 사용하여 비활성화 할 수 있습니다 --noIndexRestore.


사실, 거기에 있다 하는 명령 으로 이동 한 데이터베이스에서 다른 데이터베이스 모음. 그냥 "이동"또는 "복사"라고하지 않습니다.

컬렉션을 복사하려면 동일한 db에서 컬렉션을 복제 한 다음 복제본을 이동하십시오.

복제하려면

> use db1
> db.source_collection.find().forEach( function(x){db.collection_copy.insert(x)} );

이동:

> use admin
switched to db admin
> db.runCommand({renameCollection: 'db1.source_collection', to: 'db2.target_collection'}) // who'd think rename could move?

다른 답변은 컬렉션을 복사하는 것이 더 좋지만, 이동하려는 경우 특히 유용합니다.


mongo cli mongo doc 에서 연결 기능을 남용합니다 . 즉, 하나 이상의 연결을 시작할 수 있습니다. 동일한 서버에서 고객 콜렉션을 테스트에서 test2로 복사하려는 경우. 먼저 몽고 껍질을 시작합니다

use test
var db2 = connect('localhost:27017/test2')

정상적인 찾기를 수행하고 처음 20 개 레코드를 test2에 복사하십시오.

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

또는 일부 기준으로 필터링

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

localhost를 IP 또는 호스트 이름으로 변경하여 원격 서버에 연결하십시오. 이것을 사용하여 테스트를 위해 테스트 데이터를 테스트 데이터베이스에 복사합니다.


두 개의 원격 mongod 인스턴스 사이에

{ cloneCollection: "<collection>", from: "<hostname>", query: { <query> }, copyIndexes: <true|false> } 

http://docs.mongodb.org/manual/reference/command/cloneCollection/을 참조 하십시오.


나는 보통 할 것입니다 :

use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });

이 질문에 대한 답변은 받았지만 커서가 스트림되어 컬렉션이 계속 사용되는 경우 무한 커서 루프가 발생할 수 있기 때문에 개인적으로 @JasonMcCays 답변을하지 않습니다. 대신 snapshot ()을 사용합니다.

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

@bens answer도 좋은 답변이며 컬렉션의 핫 백업뿐만 아니라 mongorestore는 동일한 mongod를 공유 할 필요가 없습니다.


This might be just a special case, but for a collection of 100k documents with two random string fields (length is 15-20 chars), using a dumb mapreduce is almost twice as fast as find-insert/copyTo:

db.coll.mapReduce(function() { emit(this._id, this); }, function(k,vs) { return vs[0]; }, { out : "coll2" })

You can use aggregation framework to resolve your issue

db.oldCollection.aggregate([{$out : "newCollection"}])

It shoul be noted, that indexes from oldCollection will not copied in newCollection.


Using pymongo, you need to have both databases on same mongod, I did the following:


db = original database
db2 = database to be copied to

cursor = db["<collection to copy from>"].find()
for data in cursor:
    db2["<new collection>"].insert(data)

for huge size collections, you can use Bulk.insert()

var bulk = db.getSiblingDB(dbName)[targetCollectionName].initializeUnorderedBulkOp();
db.getCollection(sourceCollectionName).find().forEach(function (d) {
    bulk.insert(d);
});
bulk.execute();

This will save a lot of time. In my case, I'm copying collection with 1219 documents: iter vs Bulk (67 secs vs 3 secs)


This won't solve your problem but the mongodb shell has a copyTo method that copies a collection into another one in the same database:

db.mycoll.copyTo('my_other_collection');

It also translates from BSON to JSON, so mongodump/mongorestore are the best way to go, as others have said.


If RAM is not an issue using insertMany is way faster than forEach loop.

var db1 = connect('<ip_1>:<port_1>/<db_name_1>')
var db2 = connect('<ip_2>:<port_2>/<db_name_2>')

var _list = db1.getCollection('collection_to_copy_from').find({})
db2.collection_to_copy_to.insertMany(_list.toArray())

In case some heroku users stumble here and like me want to copy some data from staging database to the production database or vice versa here's how you do it very conveniently (N.B. I hope there's no typos in there, can't check it atm., I'll try confirm the validity of the code asap):

to_app="The name of the app you want to migrate data to"
from_app="The name of the app you want to migrate data from"
collection="the collection you want to copy"
mongohq_url=`heroku config:get --app "$to_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
to_token=${parts[0]}; to_url=${parts[1]}; to_db=${parts[2]}
mongohq_url=`heroku config:get --app "$from_app" MONGOHQ_URL`
parts=(`echo $mongohq_url | sed "s_mongodb://heroku:__" | sed "s_[@/]_ _g"`)
from_token=${parts[0]}; from_url=${parts[1]}; from_db=${parts[2]}
mongodump -h "$from_url" -u heroku -d "$from_db" -p"$from_token" -c "$collection" -o col_dump
mongorestore -h "$prod_url" -u heroku -d "$to_app" -p"$to_token" --dir col_dump/"$col_dump"/$collection".bson -c "$collection"

You can always use Robomongo. As of v0.8.3 there is a tool that can do this by right-clicking on the collection and selecting "Copy Collection to Database"

For details, see http://blog.robomongo.org/whats-new-in-robomongo-0-8-3/

This feature was removed in 0.8.5 due to its buggy nature so you will have to use 0.8.3 or 0.8.4 if you want to try it out.


In my case, I had to use a subset of attributes from the old collection in my new collection. So I ended up choosing those attributes while calling insert on the new collection.

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

use "Studio3T for MongoDB" that have Export and Import tools by click on database , collections or specific collection download link : https://studio3t.com/download/


This can be done using Mongo's db.copyDatabase method:

db.copyDatabase(fromdb, todb, fromhost, username, password)

Reference: http://docs.mongodb.org/manual/reference/method/db.copyDatabase/

참고 : https://stackoverflow.com/questions/11554762/how-to-copy-a-collection-from-one-database-to-another-in-mongodb

반응형