# How to connect to Mongodb in local? #### » Start mongodb with docker ``` # please install docker on your local docker run --name mongodb -p 27017:27017 -d mongo ``` #### » Run the mongo images ``` # 檢查是否有mongodb image $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE mongo latest f03be0dc25f8 5 weeks ago 448MB # 檢查 mongodb container 執行 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6024e7a8bf47 mongo "docker-entrypoint.s…" 10 hours ago Up 10 hours 0.0.0.0:27017->27017/tcp mongodb # 啟動 docker container $ docker start [Container ID] # 停止 docker container $ docker stop [Container ID] ``` #### » If NOT any running container ``` # [OPTIONS]: # -i, --interactive (互動模式) # -t, --tty (配置一個終端機) # -d, --deactivate (背景執行) $ docker run -it -d mongo ``` #### » For more information click [here](https://hub.docker.com/_/mongo) ## Create a new python project #### ① Poetry create one project ``` # use poetry as package management(instead pip) $ poetry new mongoengine-tutorial # enter the project $ cd mongoengine-tutorial ``` #### ② Create the poetry.toml ``` # make sure the venv is in project dir $ echo "[virtualenvs]\nin-project = true" > poetry.toml ``` #### ③ Build the virtual environment ``` # use shell to create a .venv directory $ poetry shell # install the usage packages $ poetry install ``` #### ④ Install the mongoengine (For more information click [here](https://docs.mongoengine.org/tutorial.html)) ``` # use poetry add as the same above $ poetry add mongoengine ``` ## MongoEngine(Python) ### After start the mongodb container & create project #### ① create the main script ``` $ cd mongodb-tutorial $ touch main.py ``` #### ② import mongoengine ``` from mongoengine import ( connect, Document, StringField, ReferenceField, ListField, EmbeddedDocumentField, EmbeddedDocument, CASCADE, ) ``` #### ③ connect to the mongodb container ``` # connect('my_db', host='127.0.0.1', port=27017) connect("tumblelog") ``` #### ④ create the model(user / comment / post) for blog ``` # User model that save the user instance class User(Document): first_name = StringField(max_length=50) last_name = StringField(max_length=50) email = StringField(required=True) class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User, reverse_delete_rule=CASCADE) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment)) # allow for inherit, because of differnet type of post meta = {"allow_inheritance": True} # Polymorphism class TextPost(Post): content = StringField() class ImagePost(Post): image_path = StringField() class LinkPost(Post): link_url = StringField() ``` #### ⑤ new the user & post ``` # Ross ross = User( email="ross@example.com", first_name="Ross", last_name="Lawley") ) ross.save() # John john = User( email="john@example.com", first_name="Roe", last_name="Kail") ) john.save() # create two comments (EmbbededDcoument won't be save) msg1 = Comment( name="jamie", content="What is the price?" ) msg2 = Comment( name="howard", content="Where to buy it?" ) message.save() # create the text post post1 = TextPost( title="Fun with MongoEngine", author="john", comment=[msg1, msg2], content="Took a look at MongoEngine today, looks pretty cool.", tags = ["mongodb", "mongoengine"] ) post1.save() # create the link post post2 = LinkPost( title="MongoEngine Documentation", author=ross, link_url = "http://docs.mongoengine.com/" ) post2.tags = ["mongoengine"] post2.save() for post in Post.objects: print(post.to_json() ``` #### ⑥ run the main.py script ``` $ python3 main.py # Output { "_id":{ "$oid":"608f4fe0d510f3eb1f733a44" }, "_cls":"Post.TextPost", "title":"Fun with MongoEngine", "author":"john", "tags":[ "mongodb", "mongoengine" ], "comments":[ { "content":"How's going?", "name":"jamie" }, { "content":"What are you doing?", "name":"howard" } ], "content":"Took a look at MongoEngine today, looks pretty cool." } { "_id":{ "$oid":"608f509657dc7ce331a9bf42" }, "_cls":"Post.LinkPost", "title":"MongoEngine Documentation", "author":{ "$oid":"608f509657dc7ce331a9bf3f" }, "tags":[ "mongoengine" ], "comments":[ ], "link_url":"http://docs.mongoengine.com/" } ``` ### Reference: - [mongodb docker images](https://hub.docker.com/_/mongo) - [mongoengine](https://docs.mongoengine.org/tutorial.html#getting-started) ###### tags: `mongodb`