MonogoDB 查询小结

MonogoDB是一种NoSQL数据库

优点:

   1.数据的存储以json的文档进行存储(面向文档存储)

   2.聚合框架查询速度快

        3.高效存储二进制大对象

缺点:

  1.不支持事务

       2.文件存储空间占用过大

案例学习

例1:单个变量查询(查找出制造商字段为“Porsche”的所有汽车的查询)

{"layout" : "rear mid-engine rear-wheel-drive layout","name" : "Porsche Boxster","productionYears" : [ ],"modelYears" : [ ],"bodyStyle" : "roadster","assembly" : ["Finland","Germany","Stuttgart","Uusikaupunki"],"class" : "sports car","manufacturer" : "Porsche"
}
def porsche_query(): #{'字段名':'字段值'}query = {'manufacturer':'Porsche'}return query

例2:范围查询 (找出在二十一世纪建成的所有城市注意运算符 $gte,$lte)

{'areaCode': ['916'],'areaLand': 109271000.0,'country': 'United States','elevation': 13.716,'foundingDate': datetime.datetime(2000, 7, 1, 0, 0),'governmentType': ['Council\u2013manager government'],'homepage': ['http://elkgrovecity.org/'],'isPartOf': ['California', u'Sacramento County California'],'lat': 38.4383,'leaderTitle': 'Chief Of Police','lon': -121.382,'motto': 'Proud Heritage Bright Future','name': 'City of Elk Grove','population': 155937,'postalCode': '95624 95757 95758 95759','timeZone': ['Pacific Time Zone'],'utcOffset': ['-7', '-8']
}
def range_query():
#使用$gt,$lt来限定查询的条件的范围 query
= {'foundingDate':{'$gte':datetime(2001,1,1),'$lt':datetime(2100,12,31)}}return query

例3:找出在德国、英国或日本组装的所有汽车

{"layout" : "rear mid-engine rear-wheel-drive layout","name" : "Porsche Boxster","productionYears" : [ ],"modelYears" : [ ],"bodyStyle" : "roadster","assembly" : ["Finland","Germany","Stuttgart","Uusikaupunki"],"class" : "sports car","manufacturer" : "Porsche"
}
def in_query():
#使用$in来找出满足调节的集合 query
= {'assembly':{'$in':['Germany','England','Japan']}}return query

例4:点表示法 找出宽度大于 2.5 的所有汽车 

{"_id" : ObjectId("52fd438b5a98d65507d288cf"),"engine" : "Crawler-transporter__1","dimensions" : {"width" : 34.7472,"length" : 39.9288,"weight" : 2721000},"transmission" : "16 traction motors powered by four  generators","modelYears" : [ ],"productionYears" : [ ],"manufacturer" : "Marion Power Shovel Company","name" : "Crawler-transporter"
}
def dot_query():
#使用.来表示父节点中的子节点query
= {'dimensions.width':{'$gt':2.5}}return query

聚合框架查询

例5:找出创建推特时最常用的应用

思路语法:$group分组,创建一个变量count,使用$sum计算分组后的数据的条数

示例文件

{"_id" : ObjectId("5304e2e3cc9e684aa98bef97"),"text" : "First week of school is over :P","in_reply_to_status_id" : null,"retweet_count" : null,"contributors" : null,"created_at" : "Thu Sep 02 18:11:25 +0000 2010","geo" : null,"source" : "web","coordinates" : null,"in_reply_to_screen_name" : null,"truncated" : false,"entities" : {"user_mentions" : [ ],"urls" : [ ],"hashtags" : [ ]},"retweeted" : false,"place" : null,"user" : {"friends_count" : 145,"profile_sidebar_fill_color" : "E5507E","location" : "Ireland :)","verified" : false,"follow_request_sent" : null,"favourites_count" : 1,"profile_sidebar_border_color" : "CC3366","profile_image_url" : "http://a1.twimg.com/profile_images/1107778717/phpkHoxzmAM_normal.jpg","geo_enabled" : false,"created_at" : "Sun May 03 19:51:04 +0000 2009","description" : "","time_zone" : null,"url" : null,"screen_name" : "Catherinemull","notifications" : null,"profile_background_color" : "FF6699","listed_count" : 77,"lang" : "en","profile_background_image_url" : "http://a3.twimg.com/profile_background_images/138228501/149174881-8cd806890274b828ed56598091c84e71_4c6fd4d8-full.jpg","statuses_count" : 2475,"following" : null,"profile_text_color" : "362720","protected" : false,"show_all_inline_media" : false,"profile_background_tile" : true,"name" : "Catherine Mullane","contributors_enabled" : false,"profile_link_color" : "B40B43","followers_count" : 169,"id" : 37486277,"profile_use_background_image" : true,"utc_offset" : null},"favorited" : false,"in_reply_to_user_id" : null,"id" : NumberLong("22819398300")
}
def make_pipeline():pipeline = [
# 1.根据source进行分组,然后统计出每个分组的数量,放在count中
# 2.根据count字段降序排列
{
'$group':{'_id':'$source','count':{'$sum':1}}},{'$sort':{'count':-1}}]return pipeline

例6:找出巴西利亚时区的用户,哪些用户发推次数不低于 100 次,哪些用户的关注者数量最多

def make_pipeline():#1.使用$match将数据进行筛选
#2.使用$project(投影运算),获取结果的返回值
#3.使用$sort根据followers的值降序排列
#4.使用$limit来限制展示的条数,第一条就是满足条件的结果
pipeline = [{'$match':{'user.time_zone':'Brasilia','user.statuses_count':{'$gte':100}}},{'$project':{'followers':'$user.followers_count','screen_name':'$user.screen_name','tweets':'$user.statuses_count'}},{'$sort':{'followers':-1}},{'$limit':1}]return pipeline

例7:找出印度的哪个地区包括的城市最多

$match进行条件筛选,类似SQL语法的where

$unwind对列表的数据进行拆分,如果数据以列表的形式存放,$unwind会将列表每一项单独和文件进行关联

$sort对文件中的元素进行排序

示例文件

{"_id" : ObjectId("52fe1d364b5ab856eea75ebc"),"elevation" : 1855,"name" : "Kud","country" : "India","lon" : 75.28,"lat" : 33.08,"isPartOf" : ["Jammu and Kashmir","Udhampur district"],"timeZone" : ["Indian Standard Time"],"population" : 1140
}
def make_pipeline():#1.根据$match筛选出国家
#2.根据$unwind将列表形式的字段进行拆分
#3.根据$group将拆分的项进行分组,并统计出总数count
#4.根据$sort将总数count进行降序排列,找出结果集
pipeline = [{'$match':{'country':'India'}},{'$unwind':'$isPartOf'},{'$group':{'_id':'$isPartOf','count':{'$sum':1}}},{'$sort':{'count':-1}}]return pipeline

例8:找出每个用户的所有推特文本数量,仅数出推特数量在前五名的用户。

$push将每一项数据聚合成列表(允许重复的元素)

$addToSet将每一项数据聚合成列表(允许重复的元素)

def make_pipeline():#1.使用$group根据screen_name进行分组
#2.使用$push将所有的text的值放入到tweet_texts中
#3.使用$sum统计出总数
#4.使用$sort将总数count进行降序排列
#5.使用$limit获取前5的用户
pipeline = [{'$group':{'_id':'$user.screen_name','tweet_texts':{'$push':'$text'},'count':{'$sum':1}}},{'$sort':{'count':-1}},{'$limit':5}]return pipeline

例9:找出印度各个地区的平均人口数量是多少

def make_pipeline():#1.使用$match筛选出国家India
#2.使用$unwind对isPartOf进行拆分
#3.使用$group将isPartOf进行分组,在使用$avg计算出平均人口
#4.使用$group将avg的值进行展示
pipeline = [{'$match':{'country':'India'}},{'$unwind':'$isPartOf'},{'$group':{'_id':'$isPartOf','avgp':{'$avg':'$population'}}},{'$group':{'_id':'India Regional City Population avg','avg':{'$avg':'$avgp'}}}]return pipeline

练习

习题集03

1.仅处理 FIELDS 字典中作为键的字段,并返回清理后的值字典列表

需求:

  1.根据 FIELDS 字典中的映射更改字典的键

  2.删掉“rdf-schema#label”中的小括号里的多余说明,例如“(spider)”

  3.如果“name”为“NULL”,或包含非字母数字字符,将其设为和“label”相同的值

  4.如果字段的值为“NULL”,将其转换为“None”

  5.如果“synonym”中存在值,应将其转换为数组(列表),方法是删掉“{}”字符,并根据“|” 拆分字符串。剩下的清理方式将由你自行决定,例如删除前缀“*”等。如果存在单数同义词,值应该依然是列表格式。    

  6.删掉所有字段前后的空格(如果有的话)

  7.输出结构应该如下所示

[ { 'label': 'Argiope','uri': 'http://dbpedia.org/resource/Argiope_(spider)','description': 'The genus Argiope includes rather large and spectacular spiders that often ...','name': 'Argiope','synonym': ["One", "Two"],'classification': {'family': 'Orb-weaver spider','class': 'Arachnid','phylum': 'Arthropod','order': 'Spider','kingdom': 'Animal','genus': None}},{ 'label': ... , }, ...
]
import codecs
import csv
import json
import pprint
import reDATAFILE = 'arachnid.csv'
FIELDS ={'rdf-schema#label': 'label','URI': 'uri','rdf-schema#comment': 'description','synonym': 'synonym','name': 'name','family_label': 'family','class_label': 'class','phylum_label': 'phylum','order_label': 'order','kingdom_label': 'kingdom','genus_label': 'genus'}def process_file(filename, fields):#获取FIELDS字典的keys列表process_fields = fields.keys()#存放结果集data = []with open(filename, "r") as f:reader = csv.DictReader(f)#跳过文件中的前3行for i in range(3):l = reader.next()#读文件for line in reader:# YOUR CODE HERE#存放总的字典res = {}#存放key是classification的子字典res['classification'] = {}#循环FIELDS字典的keys  for field in process_fields:#获取excel中key所对应的val,条件1tmp_val = line[field].strip()#生成json数据的新key,即是FIELDS字典的valuenew_key = FIELDS[field]#条件4 if tmp_val == 'NULL':tmp_val = None#条件2if field == 'rdf-schema#label':tmp_val = re.sub(r'\(.*\)','',tmp_val).strip()#条件3if field == 'name' and line[field] == 'NULL':tmp_val = line['rdf-schema#label'].strip()#条件5if field == 'synonym' and tmp_val:tmp_val = parse_array(line[field])#子字典中所包含的的key if new_key in ['kingdom','family','order','phylum','genus','class']:#子字典中所包含的的key的valueres['classification'][new_key] = tmp_valcontinue#将新的key和val放入到res中,然后加入到列表中返回res[new_key] = tmp_valdata.append(res)return datadef parse_array(v):#解析数组#如果以{开头和}结尾,删除左右的{},并以|进行分割,最后去除每一个项的空格,返回if (v[0] == "{") and (v[-1] == "}"):v = v.lstrip("{")v = v.rstrip("}")v_array = v.split("|")v_array = [i.strip() for i in v_array]return v_arrayreturn [v]
def test():#测试函数,如果不出错,结果正确data = process_file(DATAFILE, FIELDS)print "Your first entry:"pprint.pprint(data[0])first_entry = {"synonym": None, "name": "Argiope", "classification": {"kingdom": "Animal", "family": "Orb-weaver spider", "order": "Spider", "phylum": "Arthropod", "genus": None, "class": "Arachnid"}, "uri": "http://dbpedia.org/resource/Argiope_(spider)", "label": "Argiope", "description": "The genus Argiope includes rather large and spectacular spiders that often have a strikingly coloured abdomen. These spiders are distributed throughout the world. Most countries in tropical or temperate climates host one or more species that are similar in appearance. The etymology of the name is from a Greek name meaning silver-faced."}assert len(data) == 76assert data[0] == first_entryassert data[17]["name"] == "Ogdenia"assert data[48]["label"] == "Hydrachnidiae"assert data[14]["synonym"] == ["Cyrene Peckham & Peckham"]if __name__ == "__main__":test()

 2.向MonogoDB中插入数据

import jsondef insert_data(data, db):#直接调用insert方法插入即可
arachnids = db.arachnid.insert(data)if __name__ == "__main__":from pymongo import MongoClientclient = MongoClient("mongodb://localhost:27017")db = client.exampleswith open('arachnid.json') as f:data = json.loads(f.read())insert_data(data, db)print db.arachnid.find_one()

习题集04

实例文本

{"_id" : ObjectId("52fe1d364b5ab856eea75ebc"),"elevation" : 1855,"name" : "Kud","country" : "India","lon" : 75.28,"lat" : 33.08,"isPartOf" : ["Jammu and Kashmir","Udhampur district"],"timeZone" : ["Indian Standard Time"],"population" : 1140
}

1.找出最常见的城市名

def make_pipeline():#1.使用$match过滤掉name为空的数据
#2.使用$group进行对name分组,统计出每个值的和放在count中
#3.使用$sort对count进行降序排列
#4.使用$limit 1返回最后的结果
pipeline = [{'$match':{'name':{'$ne':None}}},{'$group':{'_id':'$name','count':{'$sum':1}}},{'$sort':{'count':-1}},{'$limit':1}]return pipeline

2.经度在 75 到 80 之间的地区中,找出哪个地区包含的城市数量最多

def make_pipeline():#1.使用$match过滤出国家为India同时经度在75~80的区域
#2.使用$unwind对地区进行分割
#3.使用$group将地区进行分组,同时根据地区统计出数量
#4.使用$sort对count进行降序排列
#5.使用$limit 1返回最后的结果
pipeline = [{'$match':{'country':'India','lon':{'$gte':75,'$lte':80}}},{'$unwind':'$isPartOf'},{'$group':{'_id':'$isPartOf','count':{'$sum':1}}},{'$sort':{'count':-1}}, {'$limit':1}]return pipeline

3.计算平均人口(本题目不是很明确,意思是要计算出每个区域的平均人口)

def make_pipeline():#1.使用$unwind对地区进行分割
#2.使用$group对所有的国家和地区进行分组,同时计算国家的平均人口
#3.使用$group在对国家进行分组然后在计算每个区域的平均人口即可
pipeline = [{'$unwind':'$isPartOf'},{'$group':{'_id':{'country':'$country','region':'$isPartOf'},'avgCityPopulation':{'$avg':'$population'}}},{'$group':{'_id':'$_id.country','avgRegionalPopulation':{'$avg':'$avgCityPopulation'}}}]return pipeline

 参考:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

转载于:https://www.cnblogs.com/luhuajun/p/8022755.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/370228.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用装饰器设计模式装饰

装饰图案是广泛使用的结构图案之一。 此模式在运行时动态更改对象的功能,而不会影响对象的现有功能。 简而言之,此模式通过包装将附加功能添加到对象。 问题陈述: 想像一下我们有一个比萨饼,该比萨饼已经用番茄和奶酪烤制的情况。…

linux 内存强度测试软件,linux下的CPU、内存、IO、网络的压力测试工具与方法介绍...

使用工具stressCentos# yum -y install stressUbantu# apt-get install stress# stress --helpstress imposes certain types of compute stress on your systemUsage: stress [OPTION [ARG]] ...-?, --help show this help statement--version show version statement-v, --v…

vcpkg安装_微软牌包管理器vcpkg更新及路线图计划

蝎子vcpkg是一套跨平台,开源的C/C库管理器,今天的这篇文章是有关vcpkg主题的2020年4月博文更新。在这篇文章中,我们将分享有关vcpkg 2020.04发布版本的一些信息以及vcpkg的路线图(roadmap),我们会在这里持续地发布有关vcpkg的最新…

CSS 盒模型与box-sizing

一、盒模型 一个web页面由许多html元素组成,而每一个html元素都可以表示为一个矩形的盒子,CSS盒模型正是描述这些矩形盒子的存在。 MDN的描述: When laying out a document, the browsers rendering engine represents each element as a r…

Java课程设计 购物车系统(个人博客) 201521123052 蓝锦明

1. 团队课程设计博客链接 课程设计团队博客 2. 个人负责模块或任务说明 (1)制作图形菜单引导界面 (2)定义各获取和输出类函数 3. 自己的代码提交记录截图 4. 自己负责模块或任务详细说明 import java.text.NumberFormat; public c…

7-12(图) 社交网络图中结点的“重要性”计算(30 分)

在社交网络中,个人或单位(结点)之间通过某些关系(边)联系起来。他们受到这些关系的影响,这种影响可以理解为网络中相互连接的结点之间蔓延的一种相互作用,可以增强也可以减弱。而结点根据其所处…

linux系统的安装程序,Linux系统安装

为了不影响本机系统,建议在虚拟机上创建并安装Linux系统,本次安装centos7 64位的镜像。详细步骤如下:1、首先在虚拟机主页创建新的虚拟机。... 图1.1 2、选择自定义安装,这样方便我们更好了解虚拟机,然后点击下一步。.…

REST与Apache Camel

在Camel中公开HTTP终结点的方法有很多:jetty,tomcat,servlet,cxfrs和restlet。 其中的两个组件– cxfrs和restlet也只需几行代码即可支持REST语义。 这个简单的示例演示了如何使用camel-restlet和camel-jdbc进行CRUD操作。 四个HT…

百米路由器2登陆地址_腾达无线路由器怎么安装,真的不错

腾达无线路由器怎么安装1、WAN口连接宽带进线(即网络公司进来的线或猫出来的线,一般颜色不一样)、LAN口连接局域网内的电脑。2、设置所连接电脑的IP地址。右键点击网上邻居属性3、右键点击本地连接属性4、选择Internet协议TCP/IP属性5、点击选择自动获得IP地址和自动…

input点击链接另一个页面,各种操作。

1.链接到某页<input type"button" name"Submit" value"确 定" class"btn" οnclick"location.hreffilename.html" />2.返回(等同后退)<input name"Submit2" type"button" class"btn"…

80. Remove Duplicates from Sorted Array II

题目描述 Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice? For example, Given sorted array nums [1,1,1,2,2,3], Your function should return length 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn…

JavaFX 2 XYCharts和Java 7功能

我最喜欢的JavaFX 2功能之一是它在javafx.scene.chart包中提供的标准图表。 该软件包提供了几种不同类型的现成图表。 除了其中之一&#xff08; PieChart &#xff09;以外&#xff0c;所有其他都是“ 2轴图”&#xff08; XYChart的特定实现&#xff09;。 在本文中&#xff…

前端基础-HTML的的标签详解

阅读目录 一、head内常用标签二、 HTML语义化三、 字符实体四、 h系列标签五、 p标签六、 img标签七、 a标签八、 列表标签九、 table标签十、 form标签 一、 head内常用标签 1、meta相关 #1、指定字符集<meta charset"gbk">#2、页面描述<meta name"…

new失败跟踪函数_WinDbg预览时间线:调试器中的时间线可以允许用户记录跟踪

时间旅行调试(TTD)允许用户记录跟踪&#xff0c;这些跟踪是对程序执行的记录。时间线是执行过程中发生的事件的直观表示&#xff0c;这些事件可以是包括断点&#xff0c;内存读/写&#xff0c;函数调用和返回以及异常。使用时间线窗口可以快速查看重要事件&#xff0c;了解相对…

linux 进程的执行时间,Linux 获取进程执行时间

Linux 获取进程执行时间1 前言测试一个程序的执行时间, 时间包括用户 CPU 时间系统 CPU 时间时钟时间之前获取之前时间都是在程序的 main 函数用 time 函数实现, 这个只能粗略的计算程序的执行时间, 不能准确的获取其他时间在看 APUE 时, 书中有关程序时间测试程序, 非常正规, …

Java环境变量的设置

1.计算机->属性->高级系统设置->环境变量 2.设置JAVA_HOME和path&#xff0c;1.5之后的JDK可以不设置classpath 3.JAVA_HOME的路径是JDK的安装路径 4.在系统变量里面找到path&#xff0c;然后点击修改&#xff0c;在最后面添加%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; 5…

merge

merge语句具有按条件获取要更新或插入到表中的数据行&#xff0c;然后从1个或多个源头对表进行更新或向表中插入行两方面的能力。经常用在数据仓库中移动大量数据。 语法: merge<hint> into<table_name> using<table_view_or_query> on<condition> whe…

可以优化同步吗?

总览 有一个常见的误解&#xff0c;因为JIT很智能&#xff0c;并且可以消除对象的同步&#xff0c;而该对象仅存在于不影响性能的方法中。 比较StringBuffer和StringBuilder的测试 这两个类基本上做相同的事情&#xff0c;除了一个是同步的&#xff08;StringBuffer&#xff0…

perl exe执行提示缺少文件解决方法

在项目开发中&#xff0c;使用perl语言编译的exe可执行文件;在项目中使用了XML::LibXML模块&#xff1b;发现exe在本机电脑执行正常&#xff0c;但在其他同事执行时却提示缺少libxml2-2.dll等文件。 问题现象&#xff1a; 无法启动此程序&#xff0c;因为计算机中丢失libxml2-2…

华为抢购助手_华为荣耀20系列手机采用的五项新科技,科普简介

5月底荣耀20系列在上海发布&#xff0c;荣耀20系列旗舰手机拥有五项荣耀自主研发的新科技&#xff0c;包括LinkTurbo网络聚合加速、超级NFC、方舟编译器、人性化YOYO智慧生命体&#xff0c;超级蓝牙。下面分别介绍一下这五项新科技。LinkTurbo网络聚合加速先来科普一下LinkTurb…