简体   繁体   中英

Update a local python dictionary using mongo syntax, without mongo

I have a codebase that uses mongo. I want to add a caching layer in between where the persistence code is called and the actual mongo db, primarily so that I can use readPreference=secondaryPreferred without breaking the rest of my app (which depends on some level of strong read-after-write consistency).

Is there a way for me to take a potentially-nested dictionary and apply mongodb update syntax without necessarily using mongo itself?

For example, I might have code like:

cache = {}

def _add_to_cache(key, doc):
  cache['key'] = doc


def _update_cache(key, update):
  cache['key'] = not_mongo_lib.apply_update(cache['key'], update)

_add_to_cache('foo', {'a': {'b': 1}})
_update_cache('foo', {'$set': {'a.b': 2}})
print(cache['foo'])  # {'a': {'b': 2}}

In other words, is there a library or an implementation for utilizing mongodb update syntax outside of mongo?

Thanks to @rickhg12hs for pointing me towards mongomock . Since my goal was to implement a TTL caching layer, I ended up just using mongomock directly with a TLL index. Something like:

import mongomock

cache = mongomock.MongoClient().db.cache
cache.create_index([(CACHE_FIELD, 1)], expireAfterSeconds=10)

cache.insert_one(doc)
cache.find(query)

I ended up not needing to directly update the cache -- instead, I remove and reinsert:

def do_update(query, update):
  updated = realmongo.find_one_and_update(query, update, pymongo.AFTER)
  cache.remove(query)
  cache.insert(update)
  return updated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM