- Reference >
- JavaScript Methods >
- db.collection.copyTo()
db.collection.copyTo()¶
On this page
Definition¶
-
db.collection.copyTo(newCollection)¶ Copies all documents from collection into
newCollectionusing server-side JavaScript. IfnewCollectiondoes not exist, MongoDB creates it.Warning
When using
db.collection.copyTo()check field types to ensure that the operation does not remove type information from documents during the translation from BSON to JSON. Consider usingcloneCollection()to maintain type fidelity.
copyTo() returns the number of documents
copied. If the copy fails, it throws an exception.
Example¶
The following operation copies all documents from the source
collection into the target collection.