def store_fundamentals(data, collection: pymongo.collection.Collection): if not data: return for datum in data: if not datum: continue print(datum) instrument_id = parse_instrument_url(datum["instrument"]) doc = {**omit("instrument", datum), "instrument_id": instrument_id} try: collection.replace_one({"instrument_id": instrument_id}, doc, True) except Exception as e: print(f"Error storing fundamentals: {e}")
def update_item(collection: pymongo.collection.Collection, model: Union[Type[BaseModel], Type[dict]], old_item_id: Union[UUID, str], new_item_obj: BaseModel, *, id_key: str = "id_", projection: dict = None, raise_exc: bool = True) -> BaseModelClass: """ Update an item in the collection :param collection: Collection to query :param model: Class which the JSON in the collection represents :param old_item_id: UUID or name of item to replace :param new_item_obj: Object to place in collection :param id_key: If the UUID is stored outside of id_, specify here :param projection: Filter to exclude from mongo query result :param raise_exc: Whether to raise exception if item is not found. :return: Updated object in collection """ old_item_obj = get_item(collection, model, old_item_id, projection=projection, id_key=id_key, raise_exc=False) if old_item_obj is None and raise_exc: raise problems.DoesNotExistException("update", model.__name__, old_item_id) try: setattr(new_item_obj, id_key, getattr(old_item_obj, id_key)) r = collection.replace_one(mongo_filter(model, old_item_id, id_key=id_key), dict(new_item_obj)) if r.acknowledged: return get_item(collection, model, getattr(old_item_obj, id_key), id_key=id_key, projection=projection, raise_exc=False) except pymongo.errors.DuplicateKeyError: if raise_exc: id_name = f"{id_and_name(model, old_item_obj, id_key=id_key)} -> " \ f"{id_and_name(model, new_item_obj, id_key=id_key)}" raise problems.UniquenessException("update", model.__name__, id_name)