Does pymongo provide an API to enable a backup or export of collections and rows?
Let me answer this question in two parts
As of now, No. It does not provide a binding method for backup/mongodump
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With