Basics of touching MongoDB with MongoEngine

This article is the third day of MongoDB Advent Calendar 2013.

What is MongoEngine?

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.

What the MongoEngine can and cannot do

What you can do

Things you can't do or things that are troublesome

Let's touch

Installation

Since it is registered in pypi, install it with pip.

$ pip install mongoengine

Connection destination settings

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)

Create a document class

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.

Add documentation

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.

Get documentation

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

Document update

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

Delete document

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 thefilter ()`).

>>> Athlete.objects.all().delete()
>>> Athlete.objects.all()
[]

taro has also been removed :)

Recommended Posts

Basics of touching MongoDB with MongoEngine
Getting Started with Python Basics of Python
Basics of binarized image processing with Python
Basics of Python ①
Basics of python ①
MongoDB Basics: Getting Started with CRUD in JAVA
Basics of Python scraping basics
Impressions of touching Django
MongoDB Basics: Transaction Processing
# 4 [python] Basics of functions
Basics of network programs?
Basics of Perceptron Foundation
[Basics of Modern Mathematical Statistics with python] Chapter 1: Probability
Basics of regression analysis
[Basics of data science] Collecting data from RSS with python
Basics of python: Output
Basics of Machine Learning (Notes)
Equation of motion with sympy
[Note] Operate MongoDB with Python
Manipulating mongoDB with Python-Part 6: aggregate-
python: Basics of using scikit-learn ①
Supervised learning 1 Basics of supervised learning (classification)
Memories of fighting with Selenium
XPath Basics (1) -Basic Concept of XPath
Prediction of Nikkei 225 with Pytorch
Basics of Python × GIS (Part 1)
How to extract features of time series data with PySpark Basics
A series of amateur infrastructure engineers touching Django with Docker ③: Django admin
Solving Knapsack Problems with Google's OR-Tools-Practicing the Basics of Combinatorial Optimization Problems
[Basics of Modern Mathematical Statistics with python] Chapter 3: Typical Probability Distribution