Skip to content

Instantly share code, notes, and snippets.

@steveseguin
Created January 5, 2023 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveseguin/412e5c5087e5d4d03a1c157bb103ee19 to your computer and use it in GitHub Desktop.
Save steveseguin/412e5c5087e5d4d03a1c157bb103ee19 to your computer and use it in GitHub Desktop.
How to connect to MongoDB with Python
To connect to MongoDB with Python, you will need to use a third-party library such as PyMongo. PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python.
Here's an example of how you can use PyMongo to connect to a MongoDB database and perform some basic operations:
Copy code
import pymongo
# Connect to the database
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Choose the database and collection to use
db = client["mydatabase"]
collection = db["mycollection"]
# Insert a document into the collection
document = {"name": "John", "age": 30}
collection.insert_one(document)
# Find all documents in the collection
documents = collection.find()
# Print the documents
for doc in documents:
print(doc)
This example connects to a MongoDB instance running on localhost on the default port (27017), and inserts a single document into a collection called "mycollection". It then finds all documents in the collection and prints them.
I hope this helps! Let me know if you have any questions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment