import time from bson import Binary from pymongo import MongoClient, DESCENDING bucket = MongoClient('127.0.0.1', 27017)['test']['foo'] bucket.drop() bucket.update({'timestamp': 0}, {'$addToSet': {'_exists_caps': 'cap15'}}, upsert=True, safe=True, w=1, wtimeout=10) bucket.create_index([('timestamp', DESCENDING)], unique=True) while True: timestamp = str(int(1000000 * time.time())) bucket.update({'timestamp': timestamp}, {'$addToSet': {'_exists_foos': 'fooxxxxx'}}, upsert=True, safe=True, w=1, wtimeout=10)