深度阅读

How to Use MongoDB Database in Python

作者
作者
2023年08月22日
更新时间
16.73 分钟
阅读时间
0
阅读量

To use MongoDB in Python, you can use the Python MongoDB driver, PyMongo . Here are the basic steps:

  1. Install PyMongo: You can use pip to install PyMongo.
pip install pymongo
  1. Create a connection to the MongoDB server: You can create a connection by calling the MongoClient() constructor and passing the connection string as an argument.
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
  1. Select a database: Once you have a connection, you can select a database by name using the dictionary syntax or using attribute notation. The following code selects a database named mydatabase.
db = client['mydatabase']
  1. Create a collection: Collections in MongoDB are similar to tables in a relational database. You can create a collection by calling the create_collection() method on the database object.
collection = db.create_collection('mycollection')
  1. Insert data: You can insert data into a collection using the insert_one() or insert_many() methods.
doc1 = {'name': 'Alice', 'age': 25, 'city': 'New York'}
doc2 = {'name': 'Bob', 'age': 30, 'city': 'London'}
collection.insert_one(doc1)
collection.insert_many([doc1, doc2])
  1. Query data: You can query data from a collection using the find() method. This will return a cursor that you can iterate over to get the documents. For example:
documents = collection.find({'city': 'New York'})
for document in documents:
print(document)

These are the basic steps to use MongoDB in Python with PyMongo. There are many more things you can do, such as updating documents, deleting documents, and using aggregation pipelines.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。