Python操作MongoDB详解及实例

yipeiwu_com6年前Python基础

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操作就不是问题。

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

相关文章

Python中支持向量机SVM的使用方法详解

Python中支持向量机SVM的使用方法详解

除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做分类。因为Python中的sklearn库也集成了SVM算法,本文的运行环境是Pycha...

Python数据分析matplotlib设置多个子图的间距方法

注意,要看懂这里,必须具备简单的Python数据分析知识,必须知道matplotlib的简单使用! 例1: plt.subplot(221) # 第一行的左图 plt.subplo...

python构建自定义回调函数详解

回调函数用起来比较爽。特别是在js中,满世界全是回调,那么在python中,怎么来优雅地实现自己的回调函数呢 下面贴一个我写的例子 class BaseHandler(object)...

python中时间转换datetime和pd.to_datetime详析

python中时间转换datetime和pd.to_datetime详析

前言 我们在python对数据进行操作时,经常会选取某一时间段的数据进行分析。这里为大家介绍两个我经常用到的用来选取某一时间段数据的函数:datetime( )和pd.to_dateti...

python实现二叉查找树实例代码

本文研究的主要是python实现二叉查找树的相关内容,具体介绍及实现如下。 1. 二叉查找树的定义: 左子树不为空的时候,左子树的结点值小于根节点,右子树不为空时,右子树的结点值大于根节...