-
Notifications
You must be signed in to change notification settings - Fork 2
Crud
GeoffreyLong edited this page Jun 27, 2014
·
3 revisions
Creating an object is as simple as instantiating the object, then calling save()
:
country = Country({"name": "Canada"})
country.save()
print country._id
For performance reasons, you can also do a bulk create:
country_names = ["Sweden", "France", "United Kingdom", "Russia"]
countries = [Country({"name": name}) for name in country_names]
Country.bulk_create(countries)
There are several ways to find objects in the database:
# Find many objects (can use skip, limit, sort)
countries = Country.find({}, limit=5, skip=2, sort="name"})
# Can sort descending:
countries = Country.find({}, limit=5, skip=2, sort=[("name", warmongo.DESCENDING)])
# Can find just one object:
country = Country.find_one({"name": "Korea"})
# Can find by an ID:
country = Country.find_by_id("mongo ID")
# Can create it if it doesn't exist (note this is not atomic):
country = Country.find_or_create({"name": "Spain"})
# Can find the latest document that matches a query:
country = Country.find_latest({"population": {"$gt": 500}})
See Querying for more details on how to find things.
Works using save()
, just like creating:
country = Country.find_one({"name": "France"})
country.abbreviation = "fr"
country.save()
Warmongo does not currently support batch updates, however you can do it through the underlying pymongo collection object:
Country.collection().update(...)
Note that using pymongo will skip validation.
Use the delete
method:
c = Country.find_one({"name": "Czechoslovakia"})
c.delete()
Warmongo does not support bulk deletes at the moment, however it can be done using the underlying pymongo collection:
Country.collection().remove(...)