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 这5本书籍你必看!

想学python 这5本书籍你必看!

python是一种美丽的语言 ,应用范围也很广,有很多的人开始学习python开发,对于初学者,这里有5本经典的书籍,如果你打算用看书来学习python,这5本书无疑是很好的选择。 1....

Python threading的使用方法解析

Python threading的使用方法解析

一、 例子:我们对传参是有要求的必须传入一个元组,否则报错 import _thread as thread import time def loop1(in1): print(...

Python中集合类型(set)学习小结

set 是一个无序的元素集合,支持并、交、差及对称差等数学运算, 但由于 set 不记录元素位置,因此不支持索引、分片等类序列的操作。 初始化 复制代码 代码如下: s0 = set()...

使用go和python递归删除.ds store文件的方法

python版本:复制代码 代码如下:#!/usr/bin/env pythonimport os, sys;def walk(path):  print "cd directory:"...

对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解

对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解 列表赋值: >>> a = [1, 2, 3] >>> b = a >>&...