diff --git a/python-mongodb/mongoengine_example.py b/python-mongodb/mongoengine_example.py index c5e3236d9809d3abc2dd405e48402d74b0d98d3d..03ebea01c4c041348c2597c94e20cfab93a7f339 100644 --- a/python-mongodb/mongoengine_example.py +++ b/python-mongodb/mongoengine_example.py @@ -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) diff --git a/python-mongodb/pymongo_example.py b/python-mongodb/pymongo_example.py index c7979fec6daa6c929056940864a1c6bb434d75c6..95e2c8347a59d2594c07fff1219fff00f0cb545c 100644 --- a/python-mongodb/pymongo_example.py +++ b/python-mongodb/pymongo_example.py @@ -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)