首页 > 编程 > Python > 正文

Python使用pymongo库操作MongoDB数据库的方法实例

2019-11-25 13:13:34
字体:
来源:转载
供稿:网友

python操作mongodb数据库

# !/usr/bin/env python# -*- coding:utf-8 -*-"""使用pymongo库操作MongoDB数据库"""import pymongo# 1.连接数据库服务器,获取客户端对象mongo_client=pymongo.MongoClient('localhost',27017)# 2.获取数据库对象db=mongo_client.myDB# db=mongo_client['myDB']# 3.获取集合对象my_collection=db.myCollection# my_collection=db['myCollection']print("――"*50)# 插入文档tom={'name':'Tom','age':18,'sex':'男','hobbies':['吃饭','睡觉','打豆豆']}alice={'name':'Alice','age':19,'sex':'女','hobbies':['读书','跑步','弹吉他']}tom_id=my_collection.insert(tom)alice_id=my_collection.insert(alice)print(tom_id)print(alice_id)print("――"*50)# 查询文档cursor=my_collection.find()print(cursor.count())  # 获取文档个数for item in cursor:  print(item)print("――"*50)# 修改文档my_collection.update({'name':'Tom'},{'$set':{'hobbies':['向Alice学习读书','跟Alice一起跑步','向Alice学习弹吉他']}})for item in my_collection.find():  print(item)print("――"*50)# 删除文档# my_collection.remove({'name':'Tom'},{'justOne':0})my_collection.remove()for item in my_collection.find():  print(item)

运行结果

/usr/bin/python3.5 /home/brandon/PythonProjects/MySpider/数据存储/保存到数据库/MongoDB/使用pymongo库操作MongoDB数据库.py
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
5a56344bfc275a13874a807e
5a56344bfc275a13874a807f
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
2
{'name': 'Tom', 'sex': '男', '_id': ObjectId('5a56344bfc275a13874a807e'), 'hobbies': ['吃饭', '睡觉', '打豆豆'], 'age': 18}
{'name': 'Alice', 'sex': '女', '_id': ObjectId('5a56344bfc275a13874a807f'), 'hobbies': ['读书', '跑步', '弹吉他'], 'age': 19}
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
{'name': 'Tom', 'sex': '男', '_id': ObjectId('5a56344bfc275a13874a807e'), 'hobbies': ['向Alice学习读书', '跟Alice一起跑步', '向Alice学习弹吉他'], 'age': 18}
{'name': 'Alice', 'sex': '女', '_id': ObjectId('5a56344bfc275a13874a807f'), 'hobbies': ['读书', '跑步', '弹吉他'], 'age': 19}
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表