python - How can I backup and restore MongoDB by using pymongo? -
does pymongo provide api enable backup or export of collections , rows?
let me answer question in 2 parts
- does pymongo provide api enable backup or export of collections , rows?
as of now, no. not provide binding method backup/mongodump
- can 1 use pymongo enable backup or export of collections , rows?
yes. lets assume have collection col following documents in it
{ 'price':25, 'name':'pen' }, { 'price':20, 'name':'pencil' }, { 'price':10, 'name':'paper' }, { 'price':25000, 'name':'gold' }
our aim backup documents satisfy condition price less 100. using pymongo's find function. can done by
db.col.find({'price':{'$lt': 100}})
the above code returns cursor object. documents need backup in cursor object.
a simple way insert documents recursively call documents 1 one , insert them.
but far better method use list() on cursor , insert documents in 1 go.
cursor = db.col.find({'price':{'$lt': 100}}) db.backup.insert(list(cursor))
the backup collection's content be
{ 'price':25, 'name':'pen' }, { 'price':20, 'name':'pencil' }, { 'price':10, 'name':'paper' }
if there no requirement limit entries backup. 1 can use empty find()
cursor = db.col.find() db.backup.insert(list(cursor))
Comments
Post a Comment