Python操作MongoDB詳解及實例
由于需要在頁面展示MongoDB庫里的數據,所以考慮使用python操作MongoDB,PyMongo模塊是Python對MongoDB操作的接口包,所以首頁安裝pymongo。
1、安裝命令
pip install pymongo
2、查詢命令:
import pymongo# 創建連接client = pymongo.MongoClient(host="10.0.2.38", port=27017)# 連接probeb庫db = client['probeb']# 打印庫中所有集合名稱print(db.collection_names())# 連接到test1這個集合collection = db.test1# 這條命令是查找rssi大于srssi小于erssi,stime大于stime,小于etime的數據以stime倒敘排列sumdata = collection.find({"RSSI": {"$gt": int(srssi), "$lt": int(erssi)}, "stime": {"$gt": stime, "$lt": etime}}).sort([('stime', -1)])#這條命令是查找rssi大于srssi小于erssi,stime大于stime小于etime 且mac等于search或者dmac等于search(search是個變量, "$options":"i"是為了不區分search內容的大小寫)的數據,以stime倒敘排列sumdata = collection.find({"RSSI": {"$gt": int(srssi), "$lt": int(erssi)}, "stime": {"$gt": stime, "$lt": etime}, "$or": [{"mac": {"$regex": search, "$options":"i"}}, {"dmac": {"$regex": search,"$options":"i"}}]}).sort([('stime', -1)])# 現在查詢的結果賦值給sumdata,如果想查出具體數據,可以使用for循環for data in sumdata:  print(data)# 注意:在使用python操作MongoDB進行排序的時候,不能使用db.test1.find().sort({"name" : 1, "age" : 1}) # 否則會遇到如下異常:# TypeError: if no direction is specified, key_or_list must be an instance of list # 解決方法:# db.tes1t.find().sort([("name", 1), ("age" , 1)]) # 原因:在python中只能使用列表進行排序,不能使用字典3、插入數據
import datetime
# 插入數據account = {"AccountID":1,"UserName":"libing",'date':datetime.datetime.now()}accounts = [{"AccountID":2,"UserName":"liuw",'date':datetime.datetime.now()},       {"AccountID":3,"UserName":"urling",'date':datetime.datetime.now()}]#每條記錄插入時間都 collections.insert(account)4、總而言之,python操作MongoDB和MongoDB的命令操作大同小異。只要熟練使用MongoDB的命令操作,那么用pymongo操作就不是問題。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答