def save_document(collection, doc):
    """Saves document to given MongoDB collection.

    If document _id already exists, replaces it. Else, inserts it.

    Parameters
    ----------
    collection : mongodb.collection
        Collection to save document to.
    doc : dict
        Document to save.
    """
    if '_id' in doc and collection.find_one({'_id': doc['_id']}):
        collection.replace_one({'_id': doc['_id']}, doc)
    else:
        collection.insert_one(doc)
