Migrate from Beanie
Migrate from Beanie
Bunnet is a synchronous version of Beanie ODM. If you used Beanie before, migrating to Bunnet will be simple.
It uses synchronous interfaces instead of Beanie's async interfaces. Nearly all the syntax is the same. But there are a few significant changes.
Import
from bunnet import Document
class Product(Document):
name: str
price: float
Init
As it is a synchronous version, a sync client should be used for the initialization.
from pymongo import MongoClient
from bunnet import init_bunnet
cli = MongoClient("mongodb://localhost:27017")
db = cli.products_db
init_bunnet(database=db, document_models=[Product])
Queries
For query objects FindOne
, UpdateQuery
, and DeleteQuery
you need to call the additional run()
method at the end of the methods chain to fetch/commit. As a syntax sugar it can be replaced with ~
prefix.
Find
Get
bar = Product.get("608da169eb9e17281f0ab2ff").run()
# or
bar = ~Product.get("608da169eb9e17281f0ab2ff")
Find one
bar = Product.find_one(Product.name == "Peanut Bar").run()
# or
bar = ~Product.find_one(Product.name == "Peanut Bar")
For find many you don't need to call run()
method, as it is iterator:
for result in Product.find(search_criteria):
print(result)
# or
result = Product.find(search_criteria).to_list()
Update
Update one
Product.find_one(Product.name == "Tony's").update({"$set": {Product.price: 3.33}}).run()
# or
~Product.find_one(Product.name == "Tony's").update({"$set": {Product.price: 3.33}})
BTW update of the already fetched object works without calling the run
method as it doesn't return UpdateQuery
in result
bar = Product.find_one(Product.name == "Milka").run()
bar.update({"$set": {Product.price: 3.33}})
Update many
Product.find(Product.price <= 2).update({"$set": {Product.price: 3.33}}).run()
# or
~Product.find(Product.price <= 2).update({"$set": {Product.price: 3.33}})
Delete
Single
Product.find_one(Product.name == "Milka").delete().run()
# or
~Product.find_one(Product.name == "Milka").delete()
# or
bar = Product.find_one(Product.name == "Milka").run()
bar.delete()
Many
Product.find(Product.category.name == "Chocolate").delete().run()
# or
~Product.find(Product.category.name == "Chocolate").delete()