Skip to content
Advertisement

How can I copy one collection from MongoDB using pymongo and paste to another empty collection?

  1. I want to copy full collection (e.g. name ‘home’).
  2. Then do some changes in the ‘home’ collection or remove doc inside it (not a collection).
  3. And then replace changed ‘home’ collection to its default state from item 1.

I do next:

JavaScript

But the collection is empty.

Advertisement

Answer

The problem with your code example is that find() returns a database cursor to the collection, not all documents in the collection. So when you remove all documents from the home collection, the cursor will also point to an empty collection.

In order to copy a collection to another collection in the same server, you can utilise MongoDB Aggregation operator $match and $out

JavaScript

Using your example code, now you can do

JavaScript

Note : db.collection.copyTo() has been deprecated since MongoDB v3.0.

If you would like to copy to another MongoDB server, you can utilise db.cloneCollection(). In PyMongo it would be a command such below:

JavaScript

Depending on your overall goal, you may find MongoDB BackUp methods useful.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement