EXTERNAL_SCOPE_FILTER = { "$or": [ {"message_scope": "EXTERNAL"}, {"message_scope": {"$exists": False}}, ] } def apply_external_scope(entry_match: dict) -> dict: if "$and" in entry_match: entry_match["$and"].append(EXTERNAL_SCOPE_FILTER) return entry_match if "$or" in entry_match: existing = entry_match.pop("$or") entry_match["$and"] = [{"$or": existing}, EXTERNAL_SCOPE_FILTER] return entry_match entry_match.update(EXTERNAL_SCOPE_FILTER) return entry_match