JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Copy/Clone a Database in MongoDB

Author:JIYIK Last Updated:2025/04/10 Views:

There are many ways in which users can clone a collection to the same MongoDB database or to another MongoDB database. This MongoDB tutorial article will discuss how users can copy/clone a database and its data in MongoDB.


Copy/clone a database in MongoDB using db.collection.copyTo() command

This command uses server-side JavaScript to copy all documents from a collection to newCollection. If the collection does not exist, MongoDB generates a new collection.

If permissions are enabled, you must perform all actions on all resources to run db.collection.copyTo(). If your business requires users to run db.collection.copyTo(), build a role that grants anyAction on anyResource.

No other users should be assigned this role.

parameter type illustrate
newCollection string The name of the collection to write data to.

Check field types when using db.collection.copyTo()to verify that the operation does not remove type information from the document during BSON to JSON conversion.

Internally, db.collection.copyTo()the method uses the eval command. Therefore, db.collection.copyTo()the operation takes a global lock, which prevents any other read or write activity until db.collection.copyTo()the operation is complete.

The number of documents copied is copyTo()returned by . If the copy fails, an exception is thrown. Because copyTo()uses eval internally, the copy operation on the mongod instance will block all other operations.

For example, the following operation copies all documents from the source collection to the target collection.

db.collection1.copyTo("collection2")
  1. This command can only be run in MongoDB 4.0 or earlier.
  2. It only clones the collection to the same database.
  3. It is very slow.
  4. It does not copy collection attributes and indexes.

Copy/clone a database in MongoDB using db.collection.find().forEach() command

This command iterates over the cursor, applying a JavaScript function to each document. The prototype of the forEach() method is as follows:

db.collection.find().forEach(<function>)

forEach()The method has the following parameters:

parameter type illustrate
Function JavaScript A JavaScript function to apply to each document from the cursor. <function>The signature consists of a single argument that passes the current document to process.

example:

db.collection1.find().forEach(
function(docs){
db.collection2.insert(docs);
})
  1. This command can only clone a collection to the same server.
  2. It is very slow.
  3. It does not copy collection attributes and indexes.

Copy/clone a database in MongoDB using mongodump and mongorestore tools

To copy a database in earlier versions of MongoDB, you could use the copyDB command or its helper methods db.copyDatabase(). However, MongoDB has subsequently deprecated these.

Additionally, starting with version 4.2, MongoDB removed the copydb command and db.copyDatabase()method, so if you are using MongoDB 4.2 or later, you will not be able to use them. However, there is a different way to copy a MongoDB database.

MongoDB database tools can be used to clone a database in MongoDB. You can use the commands mongodump and mongorestore.

MongoDB Database Tools is a set of command-line tools for working with MongoDB. If you are not sure whether you have MongoDB Database Tools installed, check using a terminal or command prompt:

mongodump --version
mongorestore --version

This code basically finds the versions of mongodump and mongorestore. If you don't have them already, you can install the MongoDB database tools on your PC by following the installation instructions on the MongoDB website.

You must use your system's command line to run mongodump and mongorestore (for example, a new terminal or Command Prompt window). It should not be executed from the mongo shell.

Here is an example of database cloning code:

mongodump --archive --db=CatHotel | mongorestore --archive  --nsFrom='CatHotel.*' --nsTo='CatHouse.*'

In this case, we back up the CatHotel database and then restore all of its collections into a database called CatHouse. In other words, we clone the CatHotel database to CatHouse.

This uses mongodump to generate a database backup file, and then uses mongorestore to restore the database under a new name. First, the database is dumped to the standard output stream and piped into mongorestore.

Here's what each parameter does:

parameter illustrate
archive It writes the output to the specified archive file or to standard output (stdout) if no archive file is specified. In your case, no archive file is specified so it writes to standard output.
db It will specify the database to be backed up. In this case, you will back up the CatHotel database.
nsFrom Specifies the collection to be included in the dump file. The asterisk wildcard character ( *) indicates all collections.
nsTo Specifies the collection name to be used when restoring the database.

You can also dump all databases using mongodump and run it without any parameters. However, when you do this, the local and configuration databases are not included in the dump.

  1. This is a high-speed method.
  2. It can clone a collection to another database and server.

Copy/clone a database in MongoDB using mongoexport and mongoimport tools

The MongoDB Tools package includes the mongoexport and mongoimport tools. The tools package can be downloaded from the MongoDB Download Center.

For example, run the following command in the command line:

mongoexport.exe /host:<host> /port:<port> /db:test /collection:collection1 /out:collection1.json
mongoimport.exe /host:<host> /port:<port> /db:test /collection:collection2 /file:collection1.json
  1. This is a quick method.
  2. It can clone collections to different databases and servers.
  3. It does not copy collection attributes and indexes.

Duplicate Collection Tool for NoSQL Manager for MongoDB

Duplicate Collections is a professional feature. It allows to copy collections very quickly in the same database.

Right-click the collection1 collection in the DB Explorer and select the Duplicate collection1 Collection item in the pop-up menu.

Repeating Collection

Specify the target collection name, copy parameters, and click Copy.

Repeat Set 1

  1. This is a high-speed method.
  2. It copies the collection attributes and indexes.
  3. It can only clone collections to the same database.

Another database tool to copy collections to NoSQL Manager for MongoDB

Copying a collection to another database is a professional feature of NoSQL Manager for MongoDB Pro. It allows copying one or more collections between databases and servers.

Right-click collection1 in the DB Explorer and select the Copy collection1 Collection to another Database item from the pop-up menu.

Repeat Set 2

Specify the target database and other parameters and click Execute.

Repeat Set 3

  1. This is a quick method.
  2. It copies the collection attributes and indexes.
  3. It can replicate collections to another database and server.
  4. It can copy multiple collections at once.
  5. It cannot rename the collection.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

$ne operator in MongoDB

Publish Date:2025/04/11 Views:84 Category:MongoDB

This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val

MongoDB $Set Operator

Publish Date:2025/04/11 Views:159 Category:MongoDB

With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given

Difference between $push and $addToSet in MongoDB

Publish Date:2025/04/11 Views:63 Category:MongoDB

This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato

Sort a collection by date in MongoDB

Publish Date:2025/04/11 Views:64 Category:MongoDB

In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB

Counting records in MongoDB

Publish Date:2025/04/11 Views:146 Category:MongoDB

This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha

Pretty printing in MongoDB

Publish Date:2025/04/11 Views:150 Category:MongoDB

This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho

MongoDB Adding Elements to an Array

Publish Date:2025/04/11 Views:136 Category:MongoDB

This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values ​​to an array The $push operator is one of the various array update operators provided by MongoDB

MongoDB Search by ID

Publish Date:2025/04/11 Views:131 Category:MongoDB

The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n

MongoDB starts with a query

Publish Date:2025/04/10 Views:195 Category:MongoDB

In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial