1、插入数据
import pymongo
from pymongo import MongoClient
#创建连接对象
client = pymongo.MongoClient(host='localhost', port=27017)
# client = MongoClient('mongodb://localhost:27017/')
#指定要操作的数据库
db = client.test
# db = client['test']
#指定要操作的集合
collection = db.students
# collection = db['students']
#新建数据
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
#直接调用insert()方法插入数据
result = collection.insert(student)
print(result)
#插入多条记录
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
result = collection.insert([student1, student2])
print(result)
#推荐用insert_one()和insert_many()来分别插入单条记录和多条记录
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
2、