1. 程式人生 > >Python操作MongoDB資料庫

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}
————————————————————————————————————————————————————————————————————————————————————————————————————