MongoDB tutorial code examples

上级 13c8992c
# Description
The files in this folder provides the code for the examples discussed on: [How to Use Python to Interface With MongoDB: The Basics](https://realpython.com/blog/python/introduction-to-mongodb-and-python/) for more info.
from mongoengine import connect, Document, StringField, ListField, URLField
# Establishing a Connection
connect(db="rpblog", host="localhost", port=27017)
# Defining a Document Schema or Model
class Posts(Document):
title = StringField(required=True, max_length=70)
author = StringField(required=True, max_length=20)
contributors = ListField(StringField(max_length=20))
url = URLField(required=True)
# Creating and Saving Documents
post = Posts(
title="Beautiful Soup: Build a Web Scraper With Python",
author="Martin",
contributors=["Aldren", "Geir", "Jaya", "Joanna", "Mike"],
url="https://realpython.com/beautiful-soup-web-scraper-python/"
)
post.save() # Insert the new post
# Retrieving All the Documents
for post in Posts.objects:
print(post.title)
# Filtering Documents by Author
for post in Posts.objects(author="Alex"):
print(post.title)
import pprint
from pymongo import MongoClient
# Establishing a Connection
client = MongoClient("localhost", 27017)
# Accessing Databases
db = client.rpblog
# Accessing Collections
posts = db.posts
# Inserting a Single Document
post = {
"title": "Working With JSON Data in Python",
"author": "Lucas",
"contributors": ["Aldren", "Dan", "Joanna"],
"url": "https://realpython.com/python-json/",
}
result = posts.insert_one(post)
print(f"One post: {result.inserted_id}")
# Inserting Several Documents
post_1 = {
"title": "Python’s Requests Library (Guide)",
"author": "Alex",
"contributors": [
"Aldren",
"Brad",
"Joanna"
],
"url": "https://realpython.com/python-requests/"
}
post_2 = {
"title": "Object-Oriented Programming (OOP) in Python 3",
"author": "David",
"contributors": [
"Aldren",
"Joanna",
"Jacob"
],
"url": "https://realpython.com/python3-object-oriented-programming/"
}
new_result = posts.insert_many([post_1, post_2])
print(f"Multiple posts: {new_result.inserted_ids}")
# Retrieving All Documents
for doc in posts.find():
pprint.pprint(doc)
# Retrieving a Single Document
jon_post = posts.find_one({"author": "Jon"})
pprint.pprint(jon_post)
# Closing a Connection
with MongoClient() as client:
db = client.rpblog
for doc in db.posts.find():
pprint.pprint(doc)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册