Multiple Database¶
We can work with multiple databases within a single node. There are multiple use cases for multiple database systems. For example, if you want to implement logging on a separate database rather than the main database.
Connection¶
We learned how to establish the connection with the database in the connection chapter.
To work with multiple databases, we will use the same connect function that we used previously.
The connect function accepts two arguments. The first one is url (required string type) and the second one is databases (optional set type).
The first argument url string should have a default database. The second argument databases is optional. We can send multiple database names as needed.
# Code omitted above
def configuration():
connect(
os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb"),
databases={"logging"},
)
apply_indexes()
# Code omitted below
Full file preview
import os
from typing import Optional
from mongodb_odm import Document, apply_indexes, connect
class Log(Document):
message: Optional[str] = None
class ODMConfig:
database = "logging"
def configuration():
connect(
os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb"),
databases={"logging"},
)
apply_indexes()
def create_data():
_ = Log(message="Testing database log").create()
def retrieve_log():
for log in Log.find():
print(log)
print()
def update_log():
log = Log.find_one()
if log:
log.message = "Update log message"
log.update()
def main():
configuration()
create_data()
retrieve_log()
update_log()
if __name__ == "__main__":
main()
Model Definition¶
There is no need for any modification of your model if it will use the default database.
We will use a logging database to store all documents for Log. For the Log model, we will always use the logging database. Modification or document retrieval should happen in the logging database.
Here we define the Log model that has a field database = "logging" inside the ODMConfig of the model.
# Code omitted above
class Log(Document):
message: Optional[str] = None
class ODMConfig:
database = "logging"
# Code omitted below
Full file preview
import os
from typing import Optional
from mongodb_odm import Document, apply_indexes, connect
class Log(Document):
message: Optional[str] = None
class ODMConfig:
database = "logging"
def configuration():
connect(
os.environ.get("MONGO_URL", "mongodb://localhost:27017/testdb"),
databases={"logging"},
)
apply_indexes()
def create_data():
_ = Log(message="Testing database log").create()
def retrieve_log():
for log in Log.find():
print(log)
print()
def update_log():
log = Log.find_one()
if log:
log.message = "Update log message"
log.update()
def main():
configuration()
create_data()
retrieve_log()
update_log()
if __name__ == "__main__":
main()
Note: MongoDB does not support $lookup with different databases that are also applicable here. We are not permitted to perform $lookup with the default and logging database.