[docs]classMongoDBByteStore(BaseStore[str,bytes]):"""BaseStore implementation using MongoDB as the underlying store. Examples: Create a MongoDBByteStore instance and perform operations on it: .. code-block:: python # Instantiate the MongoDBByteStore with a MongoDB connection from langchain.storage import MongoDBByteStore mongo_conn_str = "mongodb://localhost:27017/" mongodb_store = MongoDBBytesStore(mongo_conn_str, db_name="test-db", collection_name="test-collection") # Set values for keys mongodb_store.mset([("key1", "hello"), ("key2", "workd")]) # Get values for keys values = mongodb_store.mget(["key1", "key2"]) # [bytes1, bytes1] # Iterate over keys for key in mongodb_store.yield_keys(): print(key) # Delete keys mongodb_store.mdelete(["key1", "key2"]) """
[docs]def__init__(self,connection_string:str,db_name:str,collection_name:str,*,client_kwargs:Optional[dict]=None,)->None:"""Initialize the MongoDBStore with a MongoDB connection string. Args: connection_string (str): MongoDB connection string db_name (str): name to use collection_name (str): collection name to use client_kwargs (dict): Keyword arguments to pass to the Mongo client """try:frompymongoimportMongoClientexceptImportErrorase:raiseImportError("The MongoDBStore requires the pymongo library to be ""installed. ""pip install pymongo")fromeifnotconnection_string:raiseValueError("connection_string must be provided.")ifnotdb_name:raiseValueError("db_name must be provided.")ifnotcollection_name:raiseValueError("collection_name must be provided.")self.client:MongoClient=MongoClient(connection_string,**(client_kwargsor{}))self.collection=self.client[db_name][collection_name]
[docs]defmget(self,keys:Sequence[str])->List[Optional[bytes]]:"""Get the list of documents associated with the given keys. Args: keys (list[str]): A list of keys representing Document IDs.. Returns: list[Document]: A list of Documents corresponding to the provided keys, where each Document is either retrieved successfully or represented as None if not found. """result=self.collection.find({"_id":{"$in":keys}})result_dict={doc["_id"]:doc["value"]fordocinresult}return[result_dict.get(key)forkeyinkeys]
[docs]defmset(self,key_value_pairs:Sequence[Tuple[str,bytes]])->None:"""Set the given key-value pairs. Args: key_value_pairs (list[tuple[str, Document]]): A list of id-document pairs. """frompymongoimportUpdateOneupdates=[{"_id":k,"value":v}fork,vinkey_value_pairs]self.collection.bulk_write([UpdateOne({"_id":u["_id"]},{"$set":u},upsert=True)foruinupdates])
[docs]defmdelete(self,keys:Sequence[str])->None:"""Delete the given ids. Args: keys (list[str]): A list of keys representing Document IDs.. """self.collection.delete_many({"_id":{"$in":keys}})
[docs]defyield_keys(self,prefix:Optional[str]=None)->Iterator[str]:"""Yield keys in the store. Args: prefix (str): prefix of keys to retrieve. """ifprefixisNone:fordocinself.collection.find(projection=["_id"]):yielddoc["_id"]else:fordocinself.collection.find({"_id":{"$regex":f"^{prefix}"}},projection=["_id"]):yielddoc["_id"]
[docs]classMongoDBStore(BaseStore[str,Document]):"""BaseStore implementation using MongoDB as the underlying store. Examples: Create a MongoDBStore instance and perform operations on it: .. code-block:: python # Instantiate the MongoDBStore with a MongoDB connection from langchain.storage import MongoDBStore mongo_conn_str = "mongodb://localhost:27017/" mongodb_store = MongoDBStore(mongo_conn_str, db_name="test-db", collection_name="test-collection") # Set values for keys doc1 = Document(...) doc2 = Document(...) mongodb_store.mset([("key1", doc1), ("key2", doc2)]) # Get values for keys values = mongodb_store.mget(["key1", "key2"]) # [doc1, doc2] # Iterate over keys for key in mongodb_store.yield_keys(): print(key) # Delete keys mongodb_store.mdelete(["key1", "key2"]) """
[docs]def__init__(self,connection_string:str,db_name:str,collection_name:str,*,client_kwargs:Optional[dict]=None,)->None:"""Initialize the MongoDBStore with a MongoDB connection string. Args: connection_string (str): MongoDB connection string db_name (str): name to use collection_name (str): collection name to use client_kwargs (dict): Keyword arguments to pass to the Mongo client """try:frompymongoimportMongoClientexceptImportErrorase:raiseImportError("The MongoDBStore requires the pymongo library to be ""installed. ""pip install pymongo")fromeifnotconnection_string:raiseValueError("connection_string must be provided.")ifnotdb_name:raiseValueError("db_name must be provided.")ifnotcollection_name:raiseValueError("collection_name must be provided.")self.client:MongoClient=MongoClient(connection_string,**(client_kwargsor{}))self.collection=self.client[db_name][collection_name]
[docs]defmget(self,keys:Sequence[str])->List[Optional[Document]]:"""Get the list of documents associated with the given keys. Args: keys (list[str]): A list of keys representing Document IDs.. Returns: list[Document]: A list of Documents corresponding to the provided keys, where each Document is either retrieved successfully or represented as None if not found. """result=self.collection.find({"_id":{"$in":keys}})result_dict={doc["_id"]:Document(**doc["value"])fordocinresult}return[result_dict.get(key)forkeyinkeys]
[docs]defmset(self,key_value_pairs:Sequence[Tuple[str,Document]])->None:"""Set the given key-value pairs. Args: key_value_pairs (list[tuple[str, Document]]): A list of id-document pairs. Returns: None """frompymongoimportUpdateOneupdates=[{"_id":k,"value":v.__dict__}fork,vinkey_value_pairs]self.collection.bulk_write([UpdateOne({"_id":u["_id"]},{"$set":u},upsert=True)foruinupdates])
[docs]defmdelete(self,keys:Sequence[str])->None:"""Delete the given ids. Args: keys (list[str]): A list of keys representing Document IDs.. """self.collection.delete_many({"_id":{"$in":keys}})
[docs]defyield_keys(self,prefix:Optional[str]=None)->Iterator[str]:"""Yield keys in the store. Args: prefix (str): prefix of keys to retrieve. """ifprefixisNone:fordocinself.collection.find(projection=["_id"]):yielddoc["_id"]else:fordocinself.collection.find({"_id":{"$regex":f"^{prefix}"}},projection=["_id"]):yielddoc["_id"]