zoukankan      html  css  js  c++  java
  • python模块整理19pyMongo

    一、pyMongo
    1、安装
    非标准库需要安装
    #easy_install pyMongo
    2、连接
    使用pymongo.connecttion.Connection类与MongoDB服务器连接
    from pymongo Connection
    db=Connection('localhost',27017).apachelog #这里创建连接和使用库写在一起来了
    >>> connection=pymongo.Connection('localhost',27017) #创建连接
    >>> db = connection.test_database #切换数据库
    获取collection
    >>> collection = db.test_collection
    db和collection都是延时创建的,在添加Document时才真正创建
    3、插入数据
    对于python来说,mongo的每一个文档都是一个字典
    db.test.insert({'a':[1,2,3]})
    db.test.find_One()
    文档添加,_id自动创建
    >>> import datetime
    >>> post = {"author": "Mike","text": "My first blog post!","tags": ["mongodb", "python", "pymongo"],"date": datetime.datetime.utcnow()}
    >>> posts = db.posts
    >>> posts.insert(post)
    批量插入
    >>> 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)}]
    >>> posts.insert(new_posts)
    多个文档组成列表插入
    获取所有collection(相当于SQL的show tables)
    >>> db.collection_names()
    [u'posts', u'system.indexes']
    4、查询
    获取单个文档
    >>> posts.find_one()
    查询多个文档
    >> for post in posts.find():
    post
    加条件的查询
    >>> posts.find_one({"author": "Mike"})
    高级查询
    >>> posts.find({"date": {"$lt": d}}).sort("author")
    统计数量
    >>> posts.count()
    3
    5、更新数据
    db.hourly.update({"hour":hour,"url":url},$inc:{"views":1},upsert=True)
    5、创建索引
    from pymongo import ASCENDING
    db.hourly.create_index([("hour":ASCENDING),("url":ASCENDING)],uniqe=True)

  • 相关阅读:
    ERP专用术语解释
    今天在倉庫了解系統流程
    今天会见广州用友的SALER
    人生隨緣
    今天午会见天思的客人
    父亲有过目不忘的本事
    今天会见易科(Exact,荷兰)温先生
    奥莱公司发展前途不可限量
    想念父母
    上海女人果真了得
  • 原文地址:https://www.cnblogs.com/diege/p/2755132.html
Copyright © 2011-2022 走看看