Does pymongo provide an API to enable a backup or export of collections and rows?
-
well, I meant using pymongo driver in python instead of mongodump/mongorestore commands...whypro– whypro2013-07-25 15:31:44 +00:00Commented Jul 25, 2013 at 15:31
-
PyMongo driver essentially just binds those MongoDB commands, so the root question of yours goes back to MongoDB docs, then look for associated PyMongo binding methods/functions for in-Python implementation details/examples.woozyking– woozyking2013-07-25 15:43:49 +00:00Commented Jul 25, 2013 at 15:43
-
Ok, Thank you. I'll read the documentation once more. :) I'm non-English-speaker. And I'm sorry for my poor English, so I cannot express my question exactly.whypro– whypro2013-07-25 16:13:17 +00:00Commented Jul 25, 2013 at 16:13
-
What language do you speak? There is a list of translations available to the official documentation docs.mongodb.org/manual/meta/translationwoozyking– woozyking2013-07-25 17:44:41 +00:00Commented Jul 25, 2013 at 17:44
1 Answer
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))