设为首页 收藏本站
查看: 905|回复: 0

[经验分享] 利用pymongo操作mongoDB数据库

[复制链接]

尚未签到

发表于 2015-11-11 09:46:43 | 显示全部楼层 |阅读模式
利用pymongo操作mongoDB数据库
  

#连接数据库
def get_db():
from pymongo import MongoClient
client = MongoClient('localhost:27017')
db = client.examples #'examples' here is the database name.it will be created if it does not exist.
#如果 examples不存在,那么就会新建它
return db
#插入操作
def add_city(db):
db.cities.insert({'name':'Chicago'}) #inser 插入一个字典
#获取数据
def get_city(db):
return db.cities.find_one()#从cities中返回任意一个数据
if __name__ == '__main__':
db = get_db()
add_city(db)
print get_city(db)


  


上面只是操作mongoDB数据库的最简单的一个例子。





我们基于mongoDB的应用(APP),pymongo模块,与mongoDB数据库,三者之间是什么关系呢?





我觉得可以表示为:  APP <-------------->pymongo<-----BSON-------->mongoDB   

                                                                     其中:BSON 为Binary Json

有了这个概念后,你就会理解为什么mongoDB是字典家族。





所以在mongoDB的操作中一定要建立一切皆为字典的基本认识。






步入正题,先说一下Query操作







<h2 style=&quot;margin-top: 5px; margin-bottom: 10px; line-height: 22.5px; font-family: 微软雅黑, Verdana, sans-serif, 宋体;&quot;><span style=&quot;font-weight: normal;&quot;>query = {'manuafacturer':'Porsche'}</span></h2><span style=&quot;color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap;&quot;>#字典结构表示要寻找的参数。{'manufacturer':'Porsche'}表示</span><span class=&quot;token lf&quot; style=&quot;box-sizing: border-box; color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap; outline: none !important;&quot;></span><span style=&quot;color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap;&quot;>#manufacturer ='Porsche'</span><span class=&quot;token lf&quot; style=&quot;box-sizing: border-box; color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap; outline: none !important;&quot;></span><span style=&quot;color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap;&quot;>#用SQL语句可以理解为SELECT * FROM autos WHERE manufacture='Porsche'</span>
projection = {'_id':0,'name':1}#显示为1,不显示为0
db.myautos.find(query,projection)#查找制造商为保时捷的数据,但是不显示'_id',显示'name'
db.myautos.find(query,projection).count()#返回满足条件的数据的数量从json文件导入数据库:  



在terminal下:
$mongoimport -db dbname -c collectionname --file inputfile.json
  

比较操作符:


$gt                                     $lt                                     $lte                                   $gte                            $ne    分别对应为:


大于(greater than)      小于(less than)      小于等于(less than equal)     大于等于(greater than equal)     不等于(not equal)


query = {'population':{'$gt':10000}}  #人口大于10000
query = {'population':{'$gt':10000, '$lte':20000}} #人口大于10000小于等于20000
query = {'name':{'$gt':'X', '$lte':'Z'}}#name 头字母介于X Z之间
from datetime import datetime
query = {'foundationDate':{'$gt':datetime(1840,1,1), '$lte':datetime(2049,10,1)}}
#介于1840,1,1日和2049,10,1 的时间
存在操作符$exist



query = {'governmentType':{'$exist':1}} #1表示存在
query = {'governmentType':{'$exist':0}} #0表示不存在
正则表达式操作符$regex  



query = {'motto':{'$regex':'[Ff]riendship'}}
  

$in 与 $all



query = {'modelYears':{'$in':[1965,1967,1977,1987]}}#只要存在一个就可以
query = {'modelYears':{'$all':[1965,1967,1977,1987]}}#四个必须全部同时存在




  如果数据结构为:


{'dimension':{'width':25,
              'height':30,
              'length':89}
........
}




  Query 字典可以为:


query = {'dimension.width':25}
city = db.cities.find(query)
for ele in city:
    city['dimension'] = 66
#保存修改
db.cities.save(city)




update操作


db.cities.update({'name':'michael',
                  'country':'china'},#条件
                  {'$set':{'iso':1978}})#满足条件的条目中,有'iso'属性的,其&#20540;改为1978
db.cities.update({'name':'michael',
                  'country':'china'},#条件
                  {'$unset':{'iso':1978}}) #满足条件的条目中,有'iso'属性的,删除'iso'属性
#多个修改
db.cities.update({'name':'michael',
                  'country':'china'},#条件
                  {'$set':{'iso':1978}}, multi = True)




   aggregate操作


我们考虑如下的数据结构:


{
    &quot;_id&quot; : ObjectId(&quot;5304e2e3cc9e684aa98bef97&quot;),
    &quot;text&quot; : &quot;First week of school is over :P&quot;,
    &quot;in_reply_to_status_id&quot; : null,
    &quot;retweet_count&quot; : null,
    &quot;contributors&quot; : null,
    &quot;created_at&quot; : &quot;Thu Sep 02 18:11:25 &#43;0000 2010&quot;,
    &quot;geo&quot; : null,
    &quot;source&quot; : &quot;web&quot;,
    &quot;coordinates&quot; : null,
    &quot;in_reply_to_screen_name&quot; : null,
    &quot;truncated&quot; : false,
    &quot;entities&quot; : {
        &quot;user_mentions&quot; : [ ],
        &quot;urls&quot; : [ ],
        &quot;hashtags&quot; : [ ]
    },
    &quot;retweeted&quot; : false,
    &quot;place&quot; : null,
    &quot;user&quot; : {
        &quot;friends_count&quot; : 145,
        &quot;profile_sidebar_fill_color&quot; : &quot;E5507E&quot;,
        &quot;location&quot; : &quot;Ireland :)&quot;,
        &quot;verified&quot; : false,
        &quot;follow_request_sent&quot; : null,
        &quot;favourites_count&quot; : 1,
        &quot;profile_sidebar_border_color&quot; : &quot;CC3366&quot;,
        &quot;profile_image_url&quot; : &quot;http://a1.twimg.com/profile_images/1107778717/phpkHoxzmAM_normal.jpg&quot;,
        &quot;geo_enabled&quot; : false,
        &quot;created_at&quot; : &quot;Sun May 03 19:51:04 &#43;0000 2009&quot;,
        &quot;description&quot; : &quot;&quot;,
        &quot;time_zone&quot; : null,
        &quot;url&quot; : null,
        &quot;screen_name&quot; : &quot;Catherinemull&quot;,
        &quot;notifications&quot; : null,
        &quot;profile_background_color&quot; : &quot;FF6699&quot;,
        &quot;listed_count&quot; : 77,
        &quot;lang&quot; : &quot;en&quot;,
        &quot;profile_background_image_url&quot; : &quot;http://a3.twimg.com/profile_background_images/138228501/149174881-8cd806890274b828ed56598091c84e71_4c6fd4d8-full.jpg&quot;,
        &quot;statuses_count&quot; : 2475,
        &quot;following&quot; : null,
        &quot;profile_text_color&quot; : &quot;362720&quot;,
        &quot;protected&quot; : false,
        &quot;show_all_inline_media&quot; : false,
        &quot;profile_background_tile&quot; : true,
        &quot;name&quot; : &quot;Catherine Mullane&quot;,
        &quot;contributors_enabled&quot; : false,
        &quot;profile_link_color&quot; : &quot;B40B43&quot;,
        &quot;followers_count&quot; : 169,
        &quot;id&quot; : 37486277,
        &quot;profile_use_background_image&quot; : true,
        &quot;utc_offset&quot; : null
    },
    &quot;favorited&quot; : false,
    &quot;in_reply_to_user_id&quot; : null,
    &quot;id&quot; : NumberLong(&quot;22819398300&quot;)
}




$group 操作


group = {'$group':{'_id':'$user.screen_name','count':{'$sum':1}}}
#group操作必须有个键是'_id'表示操作的对象,'$sum'表示求和操作
#上面这一行代码的意思是,统计各个'user.screen_name'的个数




$sort 操作,顾名思义,排序操作,其对某个键&#20540;进行升序或是降序操作


#接上段代码
sort = {'$sort:{'count':-1}} #按照'count'对应的&#20540;得降序排序




   将group,sort整合到aggregate函数中,就能得到我们想要的结果


pipeline = [group,sort]
result = db.tweets.aggregate(pipeline)
#result 是一个字典。result['result'] 包含处理好的数据的列表
#整个操作就是,统计各个user.screen_name的数量,并倒序排列




   上面仅仅是最简单的例子


下面我们继续讨论其他操作:


$match ,顾名思义,我更愿意叫他“过滤器”


好吧让我举个例子,我想找出数据库中谁的人气最旺!你给我个建议,怎么找到这个逗比?


¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥好好想想¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥


¥¥¥¥¥¥¥¥¥¥¥¥¥是国民老公,王思聪¥¥¥¥¥¥¥¥¥¥¥¥¥还是,臭脚,杨幂¥¥¥¥¥¥¥¥¥


¥¥¥¥¥¥¥¥¥是某个微博卖肉的小明星?¥¥¥¥¥¥¥还是传媒达人,谷大白话?¥¥¥¥¥¥¥¥¥¥¥¥


好吧,我只想到了个比&#20540;,用比&#20540;表示,是比&#20540;,不是&#36924;&#20540;


比&#20540; = 粉丝数/好友数


当然,关注数也还行,可我就是这么任性,像姜文大叔一样,怎么滴?


奥,你说,你要这样我不看了啦!


好!你不看就不看吧,小弟看了姜文大叔的电影,学了一个本事儿。


我悄悄告诉你:姜文的意思是:我拍电影不是给你看的,我是给自己看的。小弟不才,没钱拍电影,》》写博客不是给别人看的,是给自己看的。对!我在自言自语。另一个我在看博客。


扯回来$match ,不,扯回来找比&#20540;,看看我怎么找比&#20540;吧,不,是最大比&#20540;


match = {'$match':{'user.friends_count':{'$gt':0},'user.followers_count':{'$gt':0}}}
#确保 好友数和粉丝数都是正数
project = {'$project':{'ratio':{'$divide':['$user.followers_count','$user.friends_count']},
                        'screen_name':'$user.screen_name'}}
#创建'ratio'和'screen_name'两个键&#20540;,其中,'ratio'利用了'$divide'除法,对两个变量进行除法操作,当然,
#这个列表有先后顺序
#下面进行排序
sort = {'$sort':{'ratio':-1}} #降序排列
#选取第一位
limit = {'$limit':1}
#$limit 限制选择结果的个数
pipeline = [match, project, sort, limit]
result = db.tweets.aggregate(pipeline)




  $unwind 操作, 举例如下:


假设有这样的字典结构:
{
'id':'1',
'author':'jone',
'tags':['good','fun','good']
}进行db.article.aggregate操作
db.article.aggregate([{'$prject':{'author':1,'tags':1}},{'$unwind':'tags'}])结果为:
{'result':[{'_id':'XXXX','author':'jone','tags':'good'},
{'_id':'XXXX','author':'jone','tags':'fun'},
{'_id':'XXXX','author':'jone','tags':'good'}],
'ok':1}所以$unwind操作的操作对象是数组,如果不是数组会报错。他的作用就是将数组中的每个元素代替数组本身,最后产生多个item,新产生的item的数目自然就是
原来数组的长度。



$group操作
我们考虑最开始的twitter数据,如果我要找到哪一个微博文本被转发的平均次数最多,该如何写我们的aggregate呢?
首先要找到推文的hashtag,这里补充一下,上文中的twitter数据中的

&quot;entities&quot; : {
&quot;user_mentions&quot; : [ ],
&quot;urls&quot; : [ ],
&quot;hashtags&quot; : [ ]结构中,‘entiyies.hashtags’是个列表。所以我们可以进行$unwind操作
而’retweet_count‘标明了被转发的次数,进行平均计算就可以了。
unwind = {'$unwind':'$entities.hashtags'} group = {'$group':{'_id':'entities.hashtags.text','retweet_avg':{'$avg':'$retweet_avg'}}}注意:$group操作必须有'_id'属性,其次'entities.hashtags.text'还可以是自己起的名字,如’txt‘。’$avg‘是进行求平均&#20540;操作。类&#20284;的还有:
'$sum'    '$first'   '$last'   '$max' '$min'    等
接着进行排序操作,这样所有操作就是如下:
unwind = {'$unwind':'$entities.hashtags'}group = {'$group':{'_id':'$entities.hashtags.text','retweet_avg':{'$avg':'$retweet_avg'}}}sort = {'$sort':{'retweet_avg':-1}}limit = {'$limit':1}pipeLine = [unwind,group,sort,limit]db.article.aggregate(pipeLine)毛主席教导的好,有矛就有盾,既有$unwind拆分数组,就收神器组成数组。你猜他会是什么呢?
$push,   $addToSet
顾名思义,push和addToSet都是将元素组合到数组中,但是addToSet更加高级,Set是集合,所以addToSet形成的数组中没有重复元素。
push形成的数组中是可以有重复元素的。
这就是二者的不同之处。




















版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-137775-1-1.html 上篇帖子: mongo DB空间索引 下篇帖子: Mongodb数据库mac下安装、启动、停止
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表