
    ~
i                         d dl Z d dlZd dlmZmZmZmZmZmZ d dl	m
Z
 d dlmZ  ej        e          Z G d de          ZdS )    N)AsyncIteratorDictIteratorListOptionalSequence)Document)
BaseLoaderc                   2   e Zd ZdZddddddedededee         d	eee                  d
eee                  deddfdZ	de
e         fdZdee         fdZdee         fdZde
e         fdZdedefdZdee         fdZ	 ddedee         dedefdZdS )MongodbLoaderzLoad MongoDB documents.NT)filter_criteriafield_namesmetadata_names!include_db_collection_in_metadataconnection_stringdb_namecollection_namer   r   r   r   returnc                   	 ddl m} n"# t          $ r}	t          d          |	d}	~	ww xY w|st          d          |st          d          |st          d           ||          | _        || _        || _        |pg | _        |pi | _        |pg | _	        || _
        | j                            |          | _        | j                            |          | _        dS )a  
        Initializes the MongoDB loader with necessary database connection
        details and configurations.

        Args:
            connection_string (str): MongoDB connection URI.
            db_name (str):Name of the database to connect to.
            collection_name (str): Name of the collection to fetch documents from.
            filter_criteria (Optional[Dict]): MongoDB filter criteria for querying
            documents.
            field_names (Optional[Sequence[str]]): List of field names to retrieve
            from documents.
            metadata_names (Optional[Sequence[str]]): Additional metadata fields to
            extract from documents.
            include_db_collection_in_metadata (bool): Flag to include database and
            collection names in metadata.

        Raises:
            ImportError: If the motor library is not installed.
            ValueError: If any necessary argument is missing.
        r   )AsyncIOMotorClientzBCannot import from motor, please install with `pip install motor`.Nz#connection_string must be provided.zdb_name must be provided.z!collection_name must be provided.)motor.motor_asyncior   ImportError
ValueErrorclientr   r   r   r   r   r   get_databasedbget_collection
collection)
selfr   r   r   r   r   r   r   r   es
             C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langchain_community/document_loaders/mongodb.py__init__zMongodbLoader.__init__   s    @	>>>>>>> 	 	 	T 	
 ! 	DBCCC 	:8999 	B@AAA(():;;.&,".4",21R.+**733'00AAs   	 
(#(c                 N    t          j        |                                           S )a  Load data into Document objects.

        Attention:

        This implementation starts an asyncio event loop which
        will only work if running in a sync env. In an async env, it should
        fail since there is already an event loop running.

        This code should be updated to kick off the event loop from a separate
        thread if running within an async context.
        )asynciorunaload)r   s    r!   loadzMongodbLoader.loadJ   s     {4::<<(((    c              #   F  K   	 t          j                    }n7# t          $ r* t          j                    }t          j        |           Y nw xY w|                                 }	 	 |                    |                                          }|V  n# t          $ r Y dS w xY w?)a  A lazy loader for MongoDB documents.

        Attention:

        This implementation starts an asyncio event loop which
        will only work if running in a sync env. In an async env, it should
        fail since there is already an event loop running.

        This code should be updated to kick off the event loop from a separate
        thread if running within an async context.

        Yields:
            Document: A document from the MongoDB collection.
        TN)	r$   get_running_loopRuntimeErrornew_event_loopset_event_loop
alazy_loadrun_until_complete	__anext__StopAsyncIteration)r   
event_loopasync_generatordocuments       r!   	lazy_loadzMongodbLoader.lazy_loadX   s      	/ 133JJ 	/ 	/ 	/ /11J":.....	/ //++	%889R9R9T9TUU%   		s!    1AA%+B 
BBc                   K   |                                  }| j                            | j        |          2 3 d{V }|                     |          W V   6 dS )zAsynchronously yields Document objects one at a time.

        Yields:
            Document: A document from the MongoDB collection.
        N)_construct_projectionr   findr   _process_document)r   
projectiondocs      r!   r.   zMongodbLoader.alazy_loadv   s       //11
--d.BJOO 	. 	. 	. 	. 	. 	. 	.#((------- POOs   Ac                   K   g }| j                             | j                   d{V }|                                 }| j                             | j        |          2 3 d{V }|                    |                     |                     06 t          |          |k    r.t          	                    dt          |           d| d           |S )z0Asynchronously loads data into Document objects.Nz6Only partial collection of documents returned. Loaded z docs, expected .)
r   count_documentsr   r7   r8   appendr9   lenloggerwarning)r   result
total_docsr:   r;   s        r!   r&   zMongodbLoader.aload   s     ?::4;OPPPPPPPP
//11
--d.BJOO 	7 	7 	7 	7 	7 	7 	7#MM$00556666 P v;;*$$NNEf++E E7AE E E  
 s   Br;   c                 ~   |                      || j        d          }| j        r"|                    | j        | j        d           | j        Q|                      || j        d          }d |                                D             }d                    |          }nt          |          }t          ||          S )zProcess a single MongoDB document into a Document object.

        Args:
            doc: The MongoDB document dictionary to process into a Document object.
         )default)databaser   Nc                 ,    g | ]}t          |          S  )str).0values     r!   
<listcomp>z3MongodbLoader._process_document.<locals>.<listcomp>   s    ===ESZZ===r(    )page_contentmetadata)_extract_fieldsr   r   updater   r   r   valuesjoinrK   r	   )r   r;   rQ   fieldstextstexts         r!   r9   zMongodbLoader._process_document   s     ''T-@"'MM 1 	OO $"&"6    '))#t/?)LLF==V]]__===E88E??DDs88DTH====r(   c                     t          | j                  pg }t          | j                  pg }||z   }|rd |D             ndS )zuConstructs the projection dictionary for MongoDB query based
        on the specified field names and metadata names.c                     i | ]}|d S )   rJ   )rL   fields     r!   
<dictcomp>z7MongodbLoader._construct_projection.<locals>.<dictcomp>   s    111Uq111r(   N)listr   r   )r   r   r   
all_fieldss       r!   r7   z#MongodbLoader._construct_projection   sW     4+,,2d1228b >1
5?I11j1111TIr(   rF   r4   rV   rG   c                     i }|pg D ]U}|}|                     d          D ] }|                    ||          }||k    r n!|                    dd          }|||<   V|S )zAExtracts and returns values for specified fields from a document.r=   _)splitgetreplace)	r   r4   rV   rG   	extractedr\   rM   keynew_field_names	            r!   rR   zMongodbLoader._extract_fields   s     	\r 	. 	.EE{{3''  		#w//G##E $"]]344N(-In%%r(   )rF   )__name__
__module____qualname____doc__rK   r   r   r   boolr"   r   r	   r'   r   r5   r   r.   r&   r9   r7   rR   rJ   r(   r!   r   r      s       !! +//326269B 9B 9B9B 9B 	9B "$9B hsm,9B !#/9B ,09B 
9B 9B 9B 9Bv)d8n ) ) ) )8H-    <	.-"9 	. 	. 	. 	.T(^    $>T >h > > > >6Jx~ J J J J 	   	
 
     r(   r   )r$   loggingtypingr   r   r   r   r   r   langchain_core.documentsr	   )langchain_community.document_loaders.baser
   	getLoggerrh   rA   r   rJ   r(   r!   <module>rr      s      J J J J J J J J J J J J J J J J - - - - - - @ @ @ @ @ @		8	$	$z z z z zJ z z z z zr(   