def combine_events_to_queries(_mongo_events):
    """Combines pymongo.monitoring events to queries.

    CommandStartedEvent has queries information.
    CommandSuccessfulEvent has timing information.

    Iterate over events and map against mongo's request_id (the query).
    """
    queries = {}  # map on the request_id

    for event in _mongo_events:
        if event.request_id not in queries:
            try:
                connection = ProfilingQueryConnection(*event.connection_id)
            except NameError:
                connection = event.connection_id
            queries[event.request_id] = dict(  # all event types have this
                command_name=event.command_name,
                # Unpack host,
                connection=connection,
                operation_id=event.operation_id,
            )

        if isinstance(event, pymongo.monitoring.CommandStartedEvent):
            queries[event.request_id].update(
                command=sanitize_dict(event.command.to_dict()),
                database_name=event.database_name,
            )
        elif isinstance(event, pymongo.monitoring.CommandSucceededEvent):
            queries[event.request_id].update(duration=event.duration_micros / 1000)
        elif isinstance(event, pymongo.monitoring.CommandFailedEvent):
            queries[event.request_id].update(
                failure=sanitize_dict(event.failure),
                duration=event.duration_micros / 1000,
            )

    return queries.values()
Combines pymongo.monitoring events to queries.

    CommandStartedEvent has queries information.
    CommandSuccessfulEvent has timing information.

    Iterate over events and map against mongo's request_id (the query).