OPTIONS

db.collection.copyTo()

Definition

db.collection.copyTo(newCollection)

Copies all documents from collection into newCollection using server-side JavaScript. If newCollection does not exist, MongoDB creates it.

Parameter Type Description
newCollection string The name of the collection to write data to.

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 using cloneCollection() to maintain type fidelity.

copyTo() returns the number of documents copied. If the copy fails, it throws an exception.

Important

Because copyTo() uses eval internally, the copy operations will block all other operations on the mongod instance.

Example

The following operation copies all documents from the source collection into the target collection.

db.source.copyTo(target)