Reputation: 521
I'm using Mongo 3.2. I have two databases on my localhost named client1 and client2. Now client1 contains a collection named users. I want to clone this collection to client2.
I have tried:-
use client2
db.cloneCollection('localhost:27017', 'client1.users', { 'active' : true } )
This outputs
{ "ok" : 0.0, "errmsg" : "can't cloneCollection from self" }
Is cloning a collection from one db to another on the same server prohibited?
Upvotes: 1
Views: 8530
Reputation: 17915
Few things :
v4.2
you should stop using copyDB
& cloneCollection
cause they're deprecated compatibility-with-v4.2 & start using mongodump and mongorestore or mongoexport & mongoimport.I would suggest to use mongodump & mongorestore :
bson
types.bson
to json
& again mongoimport will convert json
to bson
while writing, which is why they're slow. You can use mongoexport & mongoimport when you wanted to analyze your collections data visually or use json
data for any other purpose.You can run below script in shell
declare - a collections = ("collectionName1" "collectionName2")
for i in "${collections[@]}"
do
echo "$i"
mongodump --host "All-shards" --username=uname --password password --ssl --authenticationDatabase admin --db dbname --collection "$i"
mongorestore --host=host-shard-name --port=27017 --username=uname --password=psswrd --ssl --authenticationDatabase=admin --db=dbname --collection= "$i" ./dump/dbName/"$i".bson;
done
To use mongodump, you must run mongodump against a running mongod or mongos instance. So these commands are being run expecting mongo is properly installed & path setup is good, if not you can navigate to mongo folder & run like ./mongodump
& ./mongorestore
. Above script will be useful if you wanted to backup multiple collections, You need specify few things in script like :
mongodump--host "All-shards"
-> Here you need to specify all shards if your MongoDB is a replica set, if not you can specify localhost:27017
.
mongorestore --host=host-shard-name
-> You've to specify one shard of replica set, else your localhost
, Few things here can be optional --ssl
, --username
, --password
.
bson
files respective to their collection names dumped, So you need to refer dbName
in restore command & collection name will be taken from variable i
-> ./dump/dbName/"$i".bson
Note : MongoDB v3.2
is so old & in cloud based MongoDB service Mongo-atlas it has already reached it's end of lifecycle, So please upgrade asap. If you're looking for a free mongo instance or starting with MongoDB - you can try atlas.
Upvotes: 2
Reputation: 13093
db.cloneCollection()
copies data directly between MongoDB instances.
https://docs.mongodb.com/v3.2/reference/method/db.cloneCollection/
That means you cannot clone inside the same mongod instance. Use mongoexport and mongoimport to clone your collection.
Since 4.2 MongoDb introduces $merge operator which allows copy from db1.collection
to db2.collection
.
Upvotes: 0