TR update

上级 7cf346e3
......@@ -5,7 +5,7 @@ connect(db="rpblog", host="localhost", port=27017)
# Defining a Document Schema or Model
class Posts(Document):
class Post(Document):
title = StringField(required=True, max_length=70)
author = StringField(required=True, max_length=20)
contributors = ListField(StringField(max_length=20))
......@@ -13,18 +13,18 @@ class Posts(Document):
# Creating and Saving Documents
post = Posts(
post1 = Post(
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
post1.save() # Insert the new post
# Retrieving All the Documents
for post in Posts.objects:
print(post.title)
# Retrieving All the Documents' title
for doc in Post.objects:
print(doc.title)
# Filtering Documents by Author
for post in Posts.objects(author="Alex"):
print(post.title)
for doc in Post.objects(author="Alex"):
print(doc.title)
......@@ -9,46 +9,46 @@ client = MongoClient("localhost", 27017)
db = client.rpblog
# Accessing Collections
posts = db.posts
post = db.post
# Inserting a Single Document
post = {
post1 = {
"title": "Working With JSON Data in Python",
"author": "Lucas",
"contributors": ["Aldren", "Dan", "Joanna"],
"url": "https://realpython.com/python-json/",
}
result = posts.insert_one(post)
result = post.insert_one(post1)
print(f"One post: {result.inserted_id}")
# Inserting Several Documents
post_1 = {
post2 = {
"title": "Python’s Requests Library (Guide)",
"author": "Alex",
"contributors": ["Aldren", "Brad", "Joanna"],
"url": "https://realpython.com/python-requests/",
}
post_2 = {
post3 = {
"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])
new_result = post.insert_many([post2, post3])
print(f"Multiple posts: {new_result.inserted_ids}")
# Retrieving All Documents
for doc in posts.find():
for doc in post.find():
pprint.pprint(doc)
# Retrieving a Single Document
jon_post = posts.find_one({"author": "Jon"})
jon_post = post.find_one({"author": "Jon"})
pprint.pprint(jon_post)
# Closing a Connection
with MongoClient() as client:
db = client.rpblog
for doc in db.posts.find():
for doc in db.post.find():
pprint.pprint(doc)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册