How can I back up and restore MongoDB using pymongo?

Provides pymongo API to enable backup or export of collections and rows?

+4
source share
1 answer

Let me answer this question in two parts.

  • Does pymongo provide an API for backing up or exporting collections and strings?

Not at the moment. It does not provide a binding method for backup / mongodump

  • Can pymongo be used to backup or export collections and strings?

Yes. suppose we have a col collection with the following documents in it

{ 'price':25, 'name':'pen' }, { 'price':20, 'name':'pencil' }, { 'price':10, 'name':'paper' }, { 'price':25000, 'name':'gold' } 

Our goal is to copy all documents that satisfy the condition that their price is less than 100. Using the pymongo search function. this can be done with

 db.col.find({'price':{'$lt': 100}}) 

The above code returns a cursor object. All documents that we need for backup are in this cursor object.

A simple way to insert all documents is to recursively call documents one at a time and insert them.

But a much better way is to use the list () in the cursor and paste all the documents in one go.

 cursor = db.col.find({'price':{'$lt': 100}}) db.backup.insert(list(cursor)) 

The contents of the backup will be

 { 'price':25, 'name':'pen' }, { 'price':20, 'name':'pencil' }, { 'price':10, 'name':'paper' } 

If there is no requirement to limit backup entries. You can use empty find ()

 cursor = db.col.find() db.backup.insert(list(cursor)) 
+2
source

Source: https://habr.com/ru/post/1493464/


All Articles