1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| from pymongo import MongoClient # 数据库链接,必须保证当前系统能正常访问mongodb!!! connect = MongoClient('mongodb://root:123@127.0.0.1:27017/admin') my_db = connect['mofang'] my_collections = my_db['my_collections']
# 添加一条数据 document = {'name': 'xiaoming', 'mobile': '13012345678', 'age': 16, 'sex': True} ret = my_collections.insert_one(document) print(ret.inserted_id) # 返回主键ID
# 添加多条数据 data_list = [ { "name": "xiaobai", "mobile": "13322345678","age":16,"sex":False}, { "name": "xiaohei", "mobile": "13322345678","age":20,"sex":True}, { "name": "xiaohong", "mobile": "13322345678","age":13,"sex":False}, { "name": "xiaolan", "mobile": "13322345678","age":17,"sex":True}, { "name": "xiaolv", "mobile": "13322345678","age":17,"sex":True}, { "name": "xiaolong", "mobile": "13322345678","age":16,"sex":False}, { "name": "xiaofei", "mobile": "13322345678","age":18,"sex":True}, ] ret = my_collections.insert_many(data_list) print(ret.inserted_ids)
|