将学生信息的内容(单条)插入到学生信息集合。
from pymongo import MongoClient
# 连接 MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database_name']
collection = db['your_collection_name']
# 要插入的学生信息
student = {
'name': 'John',
'age': 20,
'gender': 'Male',
'class': 'Grade 10'
}
# 插入学生信息
result = collection.insert_one(student)
# 打印插入的学生信息的 ObjectId
print(f"插入的学生信息的 ObjectId: {result.inserted_id}")
# 关闭连接
client.close()
在这个示例中,我们首先创建一个学生信息的字典 student,其中包含了学生的姓名、年龄、性别和班级等信息。
然后,我们使用 insert_one() 方法将这个学生信息插入到学生信息集合中。该方法将返回一个 InsertOneResult 对象,可以通过 inserted_id 属性来获取插入的学生信息的 ObjectId。
请注意,您需要将代码中的 'mongodb://localhost:27017/' 替换为您实际的 MongoDB 连接字符串,并将 'your_database_name' 替换为您所使用的数据库名称,将 'your_collection_name' 替换为您的集合名称。