'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 theahura