简体   繁体   English

使用 mongo 语法更新本地 python 字典,不使用 mongo

[英]Update a local python dictionary using mongo syntax, without mongo

I have a codebase that uses mongo.我有一个使用 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).我想在调用持久性代码的位置和实际的 mongo db 之间添加一个缓存层,主要是这样我就可以使用readPreference=secondaryPreferred而不会破坏我的应用程序的其余部分(这取决于某种程度的强读后写一致性)。

Is there a way for me to take a potentially-nested dictionary and apply mongodb update syntax without necessarily using mongo itself?有没有办法让我使用潜在嵌套的字典并应用 mongodb 更新语法而不必使用 mongo 本身?

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?换句话说,是否有在 mongo 之外使用 mongodb 更新语法的库或实现?

Thanks to @rickhg12hs for pointing me towards mongomock .感谢@rickhg12hs 将我指向mongomock Since my goal was to implement a TTL caching layer, I ended up just using mongomock directly with a TLL index.因为我的目标是实现一个 TTL 缓存层,所以我最终只是直接使用带有 TLL 索引的 mongomock。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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