This article is the third day of MongoDB Advent Calendar 2013.
MongoEngine is a library called ** ODM == Object Document Mapper ** that allows you to manipulate documents for MongoDB like objects. It abstracts document schema definition, retrieval, and storage.
It's very similar to the ORM in Django, and Django users will be able to use MongoDB without learning MongoDB-specific queries. maybe.
However, trying to do something in-depth requires knowledge of MongoDB.
Since it is registered in pypi, install it with pip.
$ pip install mongoengine
Use mongoengine.connect
to connect to MongoDB. To connect to a database called * mongotest *:
from mongoengine import connect
connect('mongotest')
Add arguments when specifying the host or port.
connect('mongotest', host='192.168.0.10', port=999)
Define a subclass that inherits from the mongoengine.document.Document
class. Assign mongoengine.fields. *
To each field. Field classes are defined with names similar to python object names, such as IntField and StringField.
documents.py
from mongoengine.document import Document
from mongoengine import fields
class Athlete(Document):
name = fields.StringField()
age = fields.IntField()
def __unicode__(self):
return self.name
The good thing about MongoDB is that it is schemaless, but I personally find it easier to create and operate a document class == schema. As an aside, one collection can work with multiple document classes, so the benefits of being schemaless are not spoiled.
Instantiate the Athlete class and call the save ()
method.
from documents import Athlete
#Add taro yamada and hanako yamada
athlete = Athlete(name=u"taro yamada", age=30)
athlete.save()
athlete = Athlete(name=u"hanako yamada", age=28)
athlete.save()
Looking at the mongo command ...
$ mongo mongotest
MongoDB shell version: 2.4.6
connecting to: mongotest
> show dbs
local 0.078125GB
mongotest 0.203125GB
The database is created automatically. The collection is
> show collections
athlete
system.indexes
> db.athlete.find()
{ "_id" : ObjectId("529db366bdbf568299123013"), "name" : "taro yamada", "age" : 30 }
{ "_id" : ObjectId("529db458bdbf568299123014"), "name" : "hanako yamada", "age" : 28 }
And so on, the documents are stored in the athlete collection.
Document acquisition is also performed from the Athlete class. Let's get all the records using the ʻall () method via the ʻobjects
property (which is familiar to Django users).
>>> Athlete.objects.all()
[<Athlete: taro yamada>, <Athlete: hanako yamada>]
Use the filter ()
method to add a retrieval condition.
>>> Athlete.objects.filter(age=28)
[<Athlete: hanako yamada>]
If you want to get only one document, you can use the get ()
method.
>>> Athlete.objects.get(age=28)
<Athlete: hanako yamada>
An exception is thrown if the document does not exist when the get ()
method is executed.
>>> Athlete.objects.get(name=u"inoki")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/key/.virtualenvs/mongoenginetest/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 186, in get
raise queryset._document.DoesNotExist(msg)
documents.DoesNotExist: Athlete matching query does not exist.
You can also use the count ()
method to count the number of documents.
>>> Athlete.objects.all().count()
2
To update the documentation, execute the instance's save ()
method. If there is no document, it will be added, and if there is, it will be updated.
>>> athlete = Athlete.objects.get(name=u"taro yamada")
>>> athlete.age = 50
>>> athlete.save()
<Athlete: taro yamada>
>>> athlete.age
50
Issue the delete ()
method on an instance of the Athlete class.
>>> hanako = Athlete.objects.get(age=28)
>>> hanako.delete()
>>> Athlete.objects.all()
[<Athlete: taro yamada>]
hanako has been removed :)
If you inadvertently chain the delete ()
method after the ʻall ()method, everything will disappear (even if you use the
filter ()`).
>>> Athlete.objects.all().delete()
>>> Athlete.objects.all()
[]
taro has also been removed :)
Recommended Posts