|
| 1 | +import pprint |
| 2 | + |
| 3 | +from pymongo import MongoClient |
| 4 | + |
| 5 | +# Establish a connection |
| 6 | +client = MongoClient("localhost", 27017) |
| 7 | + |
| 8 | +# Access the database |
| 9 | +db = client.rptutorials |
| 10 | + |
| 11 | +# Access a collection |
| 12 | +tutorial = db.tutorial |
| 13 | + |
| 14 | +# Insert a single document |
| 15 | +tutorial1 = { |
| 16 | + "title": "Working With JSON Data in Python", |
| 17 | + "author": "Lucas", |
| 18 | + "contributors": ["Aldren", "Dan", "Joanna"], |
| 19 | + "url": "https://realpython.com/python-json/", |
| 20 | +} |
| 21 | +result = tutorial.insert_one(tutorial1) |
| 22 | +print(f"One tutorial: {result.inserted_id}") |
| 23 | + |
| 24 | +# Insert several documents |
| 25 | +tutorial2 = { |
| 26 | + "title": "Python’s Requests Library (Guide)", |
| 27 | + "author": "Alex", |
| 28 | + "contributors": ["Aldren", "Brad", "Joanna"], |
| 29 | + "url": "https://realpython.com/python-requests/", |
| 30 | +} |
| 31 | + |
| 32 | +tutorial3 = { |
| 33 | + "title": "Object-Oriented Programming (OOP) in Python 3", |
| 34 | + "author": "David", |
| 35 | + "contributors": ["Aldren", "Joanna", "Jacob"], |
| 36 | + "url": "https://realpython.com/python3-object-oriented-programming/", |
| 37 | +} |
| 38 | + |
| 39 | +new_result = tutorial.insert_many([tutorial2, tutorial3]) |
| 40 | +print(f"Multiple tutorials: {new_result.inserted_ids}") |
| 41 | + |
| 42 | +# Retrieve all documents |
| 43 | +for doc in tutorial.find(): |
| 44 | + pprint.pprint(doc) |
| 45 | + |
| 46 | +# Retrieve a single document |
| 47 | +jon_tutorial = tutorial.find_one({"author": "Jon"}) |
| 48 | +pprint.pprint(jon_tutorial) |
| 49 | + |
| 50 | +# Close a connection |
| 51 | +with MongoClient() as client: |
| 52 | + db = client.rptutorials |
| 53 | + for doc in db.tutorial.find(): |
| 54 | + pprint.pprint(doc) |
0 commit comments