简体   繁体   中英

How to copy collection to another new collection in mongoDB

I need your help with copy one collection to another collection in different database. In first case I read data from first collection. It is ok.

您可以使用.copyTo()方法复制它:

db.collection.copyTo(newCollection)

Actually there are several ways to do this. db.collection.copyTo() is one of them but it can only be used in Mongodb 4.0 or earlier versions. From mongoDB docs:

Starting in version 4.2, MongoDB removes the eval command. The deprecated db.collection.copyTo(), which wraps the eval command, can only be run against MongoDB 4.0 or earlier versions. For behavior and example, refer to the 4.0 or earlier version of the manual.

I recommend using tools such as mongodump and mongorestore .These tools are parts of the MongoDB tools package.

You can basically use them with command line. Like this:

mongodump.exe  --host <host> --port <port> --db test --collection collection1 --out "x:\out"
mongorestore.exe  --host <host> --port <port> --db test --collection collection2 "x:\out\test\collection1.bson" 

Hope it works.

thank you. I create this: MongoClient.connect(process.env.URL_PROD, {useNewUrlParser: true, useUnifiedTopology: true}, function (err, clientP) { if (err) return console.error(err); const dbP = clientP.db(process.env.DATABAZE_PROD); dbP.collection(process.env.KOLEKCE_PROD).find().toArray(function (err, schema) { //vybere z db na produ posledni limit MongoClient.connect(process.env.URL_TEST, function (err, clientT) { const dbT = clientT.db(process.env.DATABAZE_TEST); var s = changeData(schema) dbT.collection(process.env.KOLEKCE_TEST).insertMany(s, function (err, res) { if (err) return console.error(err); }); dbT.close; }); }); dbP.close; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM