How can I copy one collection from MongoDB using pymongo and paste to another empty collection?
<ol>
<li>I want to copy full collection (e.g. name 'home').</li>
<li>Then do some changes in the 'home' collection or remove doc inside it (not a collection).</li>
<li>And then replace changed 'home' collection to its default state from item 1.</li>
</ol>

<p>I do next: </p>

<pre><code>db = client["database"]
home = db['home'].find()  # get collection.
db['home'].remove({})  # remove doc from home
for i in home:
      self.db['home'].insert(i)
</code></pre>

<p>But the collection is empty.</p>

<p>The problem with your code example is that <code>find()</code> returns a <a href="https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/" rel="nofollow">database cursor</a> to the collection, not all documents in the collection. So when you <code>remove</code> all documents from the <code>home</code> collection, the cursor will also point to an empty collection. </p>

<p>In order to copy a collection to another collection in the same server, you can utilise <a href="https://docs.mongodb.com/manual/aggregation/" rel="nofollow">MongoDB Aggregation</a> operator <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match" rel="nofollow">$match</a> and <a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/out/" rel="nofollow">$out</a></p>



<pre><code>pipeline = [ {"$match": {}}, 
             {"$out": "destination_collection"},
]
db.source_collection.aggregate(pipeline)
</code></pre>

<p>Using your example code, <strong>now</strong> you can do </p>



<pre><code>source = db["source_collection"]
destination = db["destination_collection"]

# Remove all documents, or make modifications. 
source.remove({}) 

# Restore documents from the source collection.  
for doc in destination: 
      source.insert(doc)
# or instead you can just use the same aggregation method above but reverse the collection name. 
</code></pre>

<p><em>Note</em> : <a href="https://docs.mongodb.com/v3.2/reference/method/db.collection.copyTo/" rel="nofollow">db.collection.copyTo()</a> has been deprecated since MongoDB v3.0. </p>

<p>If you would like to copy to another MongoDB server, you can utilise <a href="https://docs.mongodb.com/v3.2/reference/method/db.cloneCollection/" rel="nofollow">db.cloneCollection()</a>. In PyMongo it would be a command such below: </p>



<pre><code>db.command("cloneCollection", **{'collection': "databaseName.source_collection", 'from': "another_host:another_port"})
</code></pre>

<p>Depending on your overall goal, you may find <a href="https://docs.mongodb.com/manual/core/backups/" rel="nofollow">MongoDB BackUp methods</a> useful. </p>

python mongodb pymongo