Tori Framework introduces the object-relational mapping module for MongoDB which you may find the code in tori.db.
Warning
Even though this feature is experimental, it is tested, stable and usable to use with some restrictions:
Let’s see from the example.
First, we define the document class.
from tori.db.document import document
@document
class Character(object):
def __init__(self, name, _id=None):
self._id = _id
self.name = name
Then, define the database.
from tori.db.database import Database
db = Database('final_fantasy_tactics')
Then, define the target collection.
from tori.db.collection import Collection
character_collection = Collection(db, Character, 'character')
Now, let’s create two characters (documents), “Ramza” and “Alma”, in the collection.
ramza = Character('Ramza', 1)
alma = Character('Alma', 2)
character_collection.post(ramza)
character_collection.post(alma)
To list all characters (documents),
characters = character_collection.filter()
for character in characters:
print('{}: {}'.format(character.id, character.name))
Then, you should see:
1: Ramza
2: Alma
Now, to find “Ramza”,
ramza = character_collection.filter(name='Ramza')
for character in characters:
print('{}: {}'.format(character.id, character.name))
Then, you should see:
1: Ramza
Let’s say you want to rename “Alma” to “Luso”.
character = character_collection.filter(name='Alma')
character.name = 'Luso'
character_collection.put(character)
To delete a character (document) by ID,
character_collection.delete(2)
Note
in the future, it should work with objects.