Python *** 作MongoDB详解及实例

Python *** 作MongoDB详解及实例,第1张

概述Python *** 作MongoDB详解实例由于需要在页面展示MongoDB库里的数据,所以考虑使用python *** 作MongoDB,PyMongo模块是Python对MongoDB *** 作的接口包,所以首页安装pymongo。

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": 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 *** 作就不是问题。

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

总结

以上是内存溢出为你收集整理的Python *** 作MongoDB详解及实例全部内容,希望文章能够帮你解决Python *** 作MongoDB详解及实例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1202153.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存