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.
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.
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
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.
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.
ʻ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.
C (Create) The example of adding a new one was introduced in the first example, so we will start by reading the data.
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
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>]
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
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
}
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.
There are two records in MongoDB where name
is famous venture A
, we will fix them.
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.
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
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.
MongoEngine documentation Next time I'll write an article about creating a web service using Flask and MongoDB.
Recommended Posts