Use MongoDB ODM in Python

Preface

This article is a sequel to the article Getting Started with MongoDB in Python. It is structured so that you can understand the contents without reading the previous article. If you're interested in MongoDB, we hope you'll stay with us until the end.

Environment

MongoDB In this article, we will build the environment using Docker. If you want to install MongoDB directly locally, please refer to the previous article. : point_up_tone1:

docker-compose.yml


version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017      
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example

Launch the container.

docker-compose up -d mongo mongo-express

If you can access and display Mongo Express, the MongoDB environment construction is complete. キャプチャ.PNG

Python

The Python side uses a library called mongoengine.

pip install mongoengine

Try to connect. Try connecting to the local database that is included by default.

test.py


from mongoengine import connect

connect(db='local',
        username="root",
        password="example",
        host='192.168.99.100',
        port=27017,
        authentication_mechanism='SCRAM-SHA-1',
        authentication_source='admin'
        )

Execute it, and if there are no errors, it is successful. See here for other connection methods: point_right_tone1: Getting Started with MongoDB in Python

MongoDB ODM

What is ODM, literally object document mapping. Map objects to a document database like MongoDB. The advantage of using it is that you can bind the structure of the data.

Let's see an example

test.py



from mongoengine import connect, Document, EmbeddedDocument, \
    StringField, IntField, DateTimeField, ListField, EmbeddedDocumentField
from datetime import datetime

connect(db='company',
        username="root",
        password="example",
        host='192.168.99.100',
        port=27017,
        authentication_mechanism='SCRAM-SHA-1',
        authentication_source='admin'
        )


class Employee(EmbeddedDocument):
    """
Employee details
    """
    name = StringField(required=True)
    age = IntField(required=False)


SCALE_CHOICES = (
    ("venture", "Venture"),
    ("major", "Major")
)


class Company(Document):
    """
Company model
    """
    name = StringField(required=True, max_length=32)
    scale = StringField(required=True, choices=SCALE_CHOICES)
    created_at = DateTimeField(default=datetime.now())
    members = ListField(EmbeddedDocumentField(Employee))

If you've ever defined a model using Django or sqlalchemy, it's a familiar configuration. Let's put the data into MongoDB using the model that is actually defined. Add the following code to test.py and execute it. : point_up_tone1: You don't need to create a test database in advance.

test.py



class TestMongoEngine:
    def add_one(self):
       c_obj = Company(
           name="Famous venture",
           scale="venture",
       )
       c_obj.save()
       return c_obj


if __name__ == "__main__":
        t = TestMongoEngine()
        t.add_one()

From Mongo Express, you can see that the data has been entered.

キャプチャ.PNG

ʻEmbeddedDocumentField` is useful when you want to define more structure inside the model, so I will use it.

Modify the code added to test.py as follows and execute it again.

test.py



class TestMongoEngine:
    def add_one(self):
       member1 = Employee(
               name="memberA",
               age=40,
       )
       member2 = Employee(
               name="memberB",
               age=35,
       )
       c_obj = Company(
           name="Famous venture A",
           scale="venture",
           members=[member1, member2]
       )
       c_obj.save()
       return c_obj


if __name__ == "__main__":
        t = TestMongoEngine()
        t.add_one()

Check the results from Mongo Express. キャプチャ.PNG

CRUD using ODM

C (Create) The example of adding a new one was introduced in the first example, so we will start by reading the data.

Reading R (Retrieve) data

Single read

Read one data from the newly added database.

test.py


...
class TestMongoEngine: 
    def get_one(self):
        return Company.objects.first()

if __name__ == "__main__":
        t = TestMongoEngine()
        rest = t.get_one()
        print(rest.id)
        print(rest.name)

result


5e7ed47419d1a75baa2bc3f3
Famous venture

Read all

test.py


...
class TestMongoEngine:
    def get_more(self):
        return Company.objects.all()

if __name__ == "__main__":
        t = TestMongoEngine()
        rest = t.get_more()
        print(rest)

result

[<Company: Company object>, <Company: Company object>, <Company: Company object>]

Read by id search

test.py


...
class TestMongoEngine:
      def get_from_oid(self, oid):
          return Company.objects.filter(pk=oid).first()

if __name__ == "__main__":
        t = TestMongoEngine()
        rest = t.get_from_oid("5e7ed47419d1a75baa2bc3f3")
        print(rest.id)
        print(rest.name)

result

5e7ed47419d1a75baa2bc3f3
Famous venture

Supplement

If you want to rearrange the order when reading data, add meta to the company model.

test.py


class Company(Document):
    """
Company model
    """
    name = StringField(required=True, max_length=32)
    scale = StringField(required=True, choices=SCALE_CHOICES)
    created_at = DateTimeField(default=datetime.now())
    members = ListField(EmbeddedDocumentField(Employee))
    meta = {
        'ordering': ['-created_at']  #Add meta
    }

Documents

Update data

Single data modification

test.py


...
class TestMongoEngine:
    def update(self):
        rest = Company.objects.filter(name="Famous venture").update_one(name="Ordinary venture")
        return rest

if __name__ == "__main__":
        t = TestMongoEngine()
        rests = t.update()

After execution, you can see that the data has changed from Mongo Express. キャプチャ.PNG

Multiple data corrections

There are two records in MongoDB where name is famous venture A, we will fix them. キャプチャ.PNG

test.py


class TestMongoEngine:
    def update(self):
        rest = Company.objects.filter(name="Famous venture A").update(name="Famous venture B")
        return rest

if __name__ == "__main__":
        t = TestMongoEngine()
        rests = t.update()
        print(rests)

Execution result

2

You can also confirm that the data has been corrected from Mongo Express. キャプチャ.PNG

Delete data

Single data deletion

test.py


class TestMongoEngine:
    def delete(self):
        rest = Company.objects.filter(name="Ordinary venture").first().delete()
        return rest

if __name__ == "__main__":
        t = TestMongoEngine()
        rests = t.delete()
        print(rests)

After execution

キャプチャ.PNG

Delete multiple data

Delete the two data whose name is famous venture B.

test.py


...
class TestMongoEngine:
    def delete(self):
        rest = Company.objects.filter(name="Famous venture B").delete()
        return rest

if __name__ == "__main__":
        t = TestMongoEngine()
        rests = t.delete()
        print(rests)

Execution result

2

When I checked from Mongo Express, all the data in CompanyDB was deleted.

Postscript

MongoEngine documentation Next time I'll write an article about creating a web service using Flask and MongoDB.

Recommended Posts

Use MongoDB ODM in Python
Use config.ini in Python
Use Valgrind in Python
Use profiler in Python
Let's use def in python
Use let expression in Python
Use Measurement Protocol in Python
Use callback function in Python
Use parameter store in Python
Use HTTP cache in Python
Use list-keyed dict in Python
Use Random Forest in Python
Use regular expressions in Python
python in mongodb in descending sort
Use Spyder in Python IDE
How to use SQLite in Python
Use rospy with virtualenv in Python3
How to use Mysql in python
Use Python in pyenv with NeoVim
How to use ChemSpider in Python
How to use PubChem in Python
Use OpenCV with Python 3 in Window
Quadtree in Python --2
CURL in python
Metaprogramming in Python
[Introduction to Python] How to use class in Python?
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Use print in a Python2 lambda expression
Meta-analysis in Python
Unittest in python
Easily use your own functions in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Easy way to use Wikipedia in Python
Plink in Python
Constant in python
MongoDB for the first time in Python
Don't use \ d in Python 3 regular expressions!
Lifegame in Python.
FizzBuzz in Python
How to use __slots__ in Python class
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
Use pathlib in Maya (Python 2.7) for upcoming Python 3.7
nCr in Python.
format in python
Scons in Python3
How to use regular expressions in Python