def _patch_referenced_docs(
    dataset_name, collection_name, field_name, dry_run=False
):
    """Ensures that the referenced documents in the collection for
    the given dataset exactly match the IDs in its dataset document.
    """
    conn = get_db_conn()
    _logger = _get_logger(dry_run=dry_run)

    dataset_dict = conn.datasets.find_one({"name": dataset_name})
    if not dataset_dict:
        _logger.warning("Dataset '%s' not found", dataset_name)
        return

    dataset_id = dataset_dict["_id"]
    ids_from_dataset_list = dataset_dict.get(field_name, [])

    # {id: name} in collection_name
    doc_id_to_name = {}
    for ref_doc_dict in conn[collection_name].find(
        {"_dataset_id": dataset_id}
    ):
        try:
            doc_id_to_name[ref_doc_dict["_id"]] = ref_doc_dict["name"]
        except:
            pass

    # Make sure docs in `views` collection match IDs in `dataset_dict`
    ids_from_dataset_set = set(ids_from_dataset_list)
    ids_from_collection = set(doc_id_to_name)
    made_changes = False

    bad_ids = ids_from_dataset_set - ids_from_collection
    num_bad_ids = len(bad_ids)
    if num_bad_ids > 0:
        _logger.info(
            "Purging %d bad %s view ID(s) %s from dataset",
            num_bad_ids,
            field_name,
            bad_ids,
        )
        ids_from_dataset_list = [
            _id for _id in ids_from_dataset_list if _id not in bad_ids
        ]
        made_changes = True

    missing_ids = ids_from_collection - ids_from_dataset_set
    num_missing_docs = len(missing_ids)
    if num_missing_docs > 0:
        missing_docs = [(_id, doc_id_to_name[_id]) for _id in missing_ids]
        _logger.info(
            "Adding %d misplaced %s(s) %s back to dataset",
            num_missing_docs,
            field_name,
            missing_docs,
        )
        ids_from_dataset_list.extend(missing_ids)
        made_changes = True

    if made_changes and not dry_run:
        conn.datasets.update_one(
            {"name": dataset_name},
            {"$set": {field_name: ids_from_dataset_list}},
        )
Ensures that the referenced documents in the collection for
    the given dataset exactly match the IDs in its dataset document.
    
fiftyone/core/odm/database.py