db.cloneCollection()

Definition

  • db.cloneCollection(from, collection, query)

Deprecated since version 4.2: MongoDB deprecates cloneCollection and its helperdb.cloneCollection(). For alternatives, seeDeprecate Support for cloneCollection.

Copies data directly between MongoDB instances. Thedb.cloneCollection() method wraps thecloneCollection command and accepts thefollowing arguments:

ParameterTypeDescriptionfromstringThe address of the server to clone from.collectionstringThe collection in the MongoDB instance that you want to copy.db.cloneCollection() will only copy the collection with thisname from database of the same name as the current database theremote MongoDB instance.

If you want to copy a collection from a different database name you must usethe cloneCollection directly.querydocumentOptional. A standard query document that limits the documents copied as part of thedb.cloneCollection() operation. All queryselectors available to the find() are available here.

Behavior

mongos

mongos does not support db.cloneCollection().

Namespace

When copying the specified collection, db.cloneCollection() uses the samedatabase name in the from server as the destination database. If thecollection does not exist in the source database, db.cloneCollection() fails.

Changed in version 3.0: If the given collection already exists in the destinationmongod instance, db.cloneCollection() returns anerror.

Authorization

db.cloneCollection() cannot be used if the from server hasauthorization enabled.

FeatureCompatibilityVersion

You cannot copy data between a MongoDB 4.0 mongodinstance with featureCompatibilityVersion (FCV) 4.0and a MongoDB version 3.6 mongod instance.

Note

You cannot copy data between a MongoDB 4.0 mongodinstance (regardless of the FCV value) and a MongoDB 3.4 and earliermongod instance.

For example:

Instance 1Instance 2
Version 4.0 mongod with FCV 4.0Version 4.0 mongod with FCV 4.0Can copy data.
Version 4.0 mongod with FCV 4.0Version 4.0 mongod with FCV 3.6Can copy data.
Version 4.0 mongod with FCV 4.0Version 3.6 mongod with FCV 3.6Cannot copy data. Instance 2 must be a MongoDB version 4.0
Version 4.0 mongod with FCV 3.6Version 3.6 mongod with FCV 3.6Can copy data.
Version 4.0 mongod with FCV 3.6Version 3.6 mongod with FCV 3.4Can copy data.

In general, if the mongod instance has itsfeatureCompatibilityVersion (FCV) set to its MongoDBversion, you cannot copy data between that instance and amongod instance of an earlier MongoDB version.

Operations that copy data include:

Example

  1. use users
  2. db.cloneCollection('mongodb.example.net:27017', 'profiles',
  3. { 'active' : true } )

This operation copies the profiles collection from the usersdatabase on the server at mongodb.example.net into the usersdatabase on the local server. The operation onlycopies documents that satisfy the query { 'active' : true }.