首页 > 数据库技术 > 详细

python中操作MongoDB

时间:2020-09-18 15:39:38      阅读:50      评论:0      收藏:0      [点我收藏+]

在python中操作MongoDB

pip3 install pymongo
python3
>>> from pymongo import MongoClient
>>> client = MongoClient(‘mongodb://127.0.0.1:27017‘)
>>> db = client.school
>>> for student in db.students.find():
...     print(‘学号:‘, student[‘stuid‘])
...     print(‘姓名:‘, student[‘name‘])
...     print(‘电话:‘, student[‘tel‘])
...
学号: 1001.0
姓名: 张三
电话: 13566778899
学号: 1002.0
姓名: 王大锤
电话: 13012345678
学号: 1003.0
姓名: 白元芳
电话: 13022223333
>>> db.students.find().count()
3
>>> db.students.remove()
{‘n‘: 3, ‘ok‘: 1.0}
>>> db.students.find().count()
0
>>> coll = db.students
>>> from pymongo import ASCENDING
>>> coll.create_index([(‘name‘, ASCENDING)], unique=True)
‘name_1‘
>>> coll.insert_one({‘stuid‘: int(1001), ‘name‘: ‘张三‘, ‘gender‘: True})
<pymongo.results.InsertOneResult object at 0x1050cc6c8>
>>> coll.insert_many([{‘stuid‘: int(1002), ‘name‘: ‘王大锤‘, ‘gender‘: False}, {‘stuid‘: int(1003), ‘name‘: ‘白元芳‘, ‘gender‘: True}])
<pymongo.results.InsertManyResult object at 0x1050cc8c8>
>>> for student in coll.find({‘gender‘: True}):
...     print(‘学号:‘, student[‘stuid‘])
...     print(‘姓名:‘, student[‘name‘])
...     print(‘性别:‘, ‘男‘ if student[‘gender‘] else ‘女‘)
...
学号: 1001
姓名: 张三
性别: 男
学号: 1003
姓名: 白元芳
性别: 男
>>>

python中操作MongoDB

原文:https://www.cnblogs.com/zeeyan/p/13690618.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!