MongoDB – copyTo() Method
Important Note: As CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0.
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.
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:
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.
Example 2: In the following example, we are working with:
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.