Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

MongoDB – copyTo() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name. This method uses eval command internally.     

Important Note: As CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0.

Syntax:

db.sourceCollection.copyTo(targetCollection)                                                                   

Parameter:

It takes only the name of the target collection where you want to copy the documents of the source collection. The type of this parameter is string.

Return: 

This method returns the number of documents copied and if that process fails it throws an exception.

Example 1: In the following example, we are working with:

Database: gfg

Collections: collectionA and collectionB

The collectionA contains three documents:

The collectionB contains two documents:

Now we copy the documents of collectionA to collectionB using copyTo() method.

db.collectionA.copyTo("collectionB")

Example 2: In the following example, we are working with:

Database: gfg

Collection: sCollection

Documents: Three documents contains name and age of the students

Now we going to copy the documents of sCollection to a new collection i.e., tCollection using copyTo() method. Here, the tCollection is not present in gfg database so MongoDB create this collection.

db.sCollection.copyTo("tCollection")

My Personal Notes arrow_drop_up
Last Updated : 16 Mar, 2021
Like Article
Save Article
Similar Reads
Related Tutorials