继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

pymongo使用

RISEBY
关注TA
已关注
手记 309
粉丝 70
获赞 317

Tutorial

开始之前,安装PyMongo和Mongo。

import pymongo
client= pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
collection = db[MONGO_TABLE]

插入操作

>>> posts = db.posts>>> posts.insert(post) # 将post数据插入posts数据表

查询一条数据:

>>> posts.find_one()

批量插入

>>> new_posts = [{"author": "Mike",...        "text": "Another post!",...        "tags": ["bulk", "insert"],...        "date": datetime.datetime(2009, 11, 12, 11, 14)},...       {"author": "Eliot",...        "title": "MongoDB is fun",...        "text": "and pretty easy too!",...        "date": datetime.datetime(2009, 11, 10, 10, 45)}]>>> result = posts.insert_many(new_posts)>>> result.inserted_ids
[ObjectId('...'), ObjectId('...')]

查找多条数据:

>>> for post in posts.find():...  post
...
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}

约束查找条件:
比如查询所有作者是 “Mike”的文章:

>>> for post in posts.find({"author": "Mike"}):...  post
...
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}

多条件查询:
比如,数据有有title 和intro两个属性,查询两字段都不存在的数据:

posts.find({ '$and': [ { 'title': {'$exist': 'false'} }, { 'intro': {'$exist': 'false'} } ] })

获取集合的数据条数:

>>> posts.count()

或者说满足某种查找条件的数据条数:

>>> posts.find({"author": "Mike"}).count()

范围查找,比如说时间范围:

>>> d = datetime.datetime(2009, 11, 12, 12)>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):...  print post
...
{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}

$lt是小于的意思。

如何建立索引呢?比如说下面这个查找:

>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]u'BasicCursor'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]

建立索引:

>>> from pymongo import ASCENDING, DESCENDING>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])u'date_-1_author_1'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]u'BtreeCursor date_-1_author_1'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]

查询结果排序

>>> posts.find().sort("UserName") #默认为升序>>> posts.sort("UserName",pymongo.ASCENDING)  #升序>>> posts.sort("UserName",pymongo.DESCENDING) #降序

聚集查询结果多列排序

>>> posts.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])
修改记录
>>>  posts.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})

删除记录

>>>  posts.delete_one({"UserName":"keyword"})  # 删除满足条件的一条数据>>>  posts.delete_many({"UserName":"keyword"}) #删除满足条件的数据

筛选出不存在某字段的数据,并执行修改操作:

#筛选出所有未发布的文章,并执行发表操作
    for i in posts.find({"published": { "$exists" : False }}):        print(i['link'])#打印出文章链接
      
        posts.update({'link':i['link']},{'$set':{'published':'yes'}}) # 对匹配该链接的数据,新增字段published,并设为yes

aggregate

to_update=book_list.aggregate([
    {'$match': {'$or': [{'update': {'$lte': '2017-06-18'}}, {'update':{"$exists" : False}}]}},    #用$match筛选符合条件的数据:这里是update字段小于等于 '2017-06-18'或不存在
    {'$project':{'link':1}}    # $project:修改输出结构,这里表示只输出符合条件数据的link字段。
    #输出结构为:
    # [{'link': 'http://www.xxxxx', '_id': ObjectId('58d469f5')},
    #  {'link': 'http://www.ddddd', '_id': ObjectId('b8cf09ca')},
    #                  ... 
    # ]])

字段更名

我们发现在上面的例子里,book_list有一个名为update的字段,由于update是数据库的关键字,在具体应用时,会报关键字冲突的错误,我们需要将其更名,方法和之前的例子类似:

#筛选出所有update字段存在的数据for i in book_list.find({"update": { "$exists" : True }}):    print(i['link'])#打印出文章链接
    # 对匹配该链接的数据,将update字段更名为update_time字段
    book_list.update({'link':i['link']},{'$rename':{'update':'update_time'}})



作者:这才是真的帅气的昵称
链接:https://www.jianshu.com/p/b82181c18012


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP