Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I backup and restore MongoDB by using pymongo?

Does pymongo provide an API to enable a backup or export of collections and rows?

like image 322
whypro Avatar asked Nov 12 '22 01:11

whypro


1 Answers

Let me answer this question in two parts

  • Does pymongo provide an API to enable a backup or export of collections and rows?

As of now, No. It does not provide a binding method for backup/mongodump

  • Can one use pymongo to enable a backup or export of collections and rows?

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

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

Our aim is to backup all documents which satisfy the condition that their price is less than 100. Using pymongo's find function. this can be done by

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

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

A simple way to insert all the documents will be to recursively call the documents one by one and to insert them.

But a far better method is to use the list() on the cursor and to insert all the documents in one go.

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

The backup collection's content will be

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

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

cursor = db.col.find()
db.backup.insert(list(cursor))
like image 134
Salil Panikkaveettil Avatar answered Nov 14 '22 23:11

Salil Panikkaveettil