In a python project i am using Beanie ODM to interact with a Mongo database.
Beanie ODM supports Relations, see: Relations - Beanie Documentation
I have a cascaded document structure like this:
Countries
-> States
-> Cities
-> Shops
-> Fruits
class DB(Document):
@classmethod
async def all(cls) -> list[Self]:
return await cls.find(fetch_links=True).to_list()
class Country(DB):
name: str
states: list[Link["State"]]
class Settings:
name = "countries"
class State(DB):
name: str
cities: list[Link["City"]]
class Settings:
name = "states"
class City(DB):
name: str
shops: list[Link["Shop"]]
class Settings:
name = "cities"
class Shop(DB):
name: str
fruits: list[Link["Fruit"]]
class Settings:
name = "shops"
class Fruit(DB):
name: str
class Settings:
name = "fruits"
It seems that write operations are extremely slow on linked documents. Writing just a single Country document containing a single state, city, shop and a couple of fruit objects, takes like 1-2 seconds.
In comparison, when I omit the links and have the cascade of documents composed inside of Country, then writing operation is fast (since it is only a single document saved to the database).
The reasoning behind this cascade of linked documents is that i can easily update the Fruits document by operating directly on the Fruits collection.
Questions:
- Considering that the amount of sub-documents of Countries will be limited (max 10 States, per State max. 10 Cities, per City max. 10 Shops, per Shop max. 10 Fruits), is linking the document an advisable or is it better to simply composition the documents in Countries in regards to create, update, delete operations?
- One of the main reasons to choose links was to make it easier to update Fruits. With links, Fruits has its own database and fruits can be updated directly. With an embedded document structure, how would one update efficiently a Fruit inside a country document without iterating over each State, City, Shop and Fruit?
Thanks for your help!