Skip to content

Instantly share code, notes, and snippets.

@salilpa
Created October 23, 2013 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salilpa/7122867 to your computer and use it in GitHub Desktop.
Save salilpa/7122867 to your computer and use it in GitHub Desktop.
How to backup a collection using pymongo. Read the documents using pymongo's find and filter the result using limitimg_query Insert all the matched documents by converting the cursor to a list
from pymongo import MongoClient
from datetime import datetime
target_client = MongoClient('localhost', 12345)
from_db = target_client['existing_db']
from_col = 'collection'
to_db = target_client['backup_db']
to_col = 'backup'
def createBackup(from_db, from_col, to_db, to_col, limiting_query=None):
back_up_cursor = from_db[from_col].find(limiting_query)
to_db[to_col].insert(list(back_up_cursor))
createBackup(from_db, from_col, to_db, to_col, {'time' : {'$lt' : datetime.now()}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment