zoukankan      html  css  js  c++  java
  • mongoDB

    python 使用 mongodb

    easy_install pymongo 
    # 安装(python2.7+)
    import pymongo connection
    =pymongo.Connection('localhost',27017) # 创建连接 db = connection.test_database # 切换数据库 collection = db.test_collection # 获取collection # db和collection都是延时创建的,在添加Document时才真正创建

    文档添加, _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)
    ObjectId('...')

    批量插入

    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)
    [ObjectId('...'), ObjectId('...')]

    获取数据

    获取所有collection
    db.collection_names() # 相当于SQL的show tables
    
    获取单个文档
    posts.find_one()

    数据查询

    查询多个文档
    for post in posts.find():
    post
    
    加条件的查询
    posts.find_one({"author": "Mike"})
    
    高级查询
    posts.find({"date": {"$lt": "d"}}).sort("author")

    统计数量

    posts.count()

    加索引

    from pymongo import ASCENDING, DESCENDING
    posts.create_index([("date", DESCENDING), ("author", ASCENDING)])

    查看查询语句的性能

    posts.find({"date": {"$lt": "d"}}).sort("author").explain()["cursor"]
    posts.find({"date": {"$lt": "d"}}).sort("author").explain()["nscanned"]
  • 相关阅读:
    mysql显示乱码
    aws常用命令
    Hive分析窗口函数(一) SUM,AVG,MIN,MAX
    Hive函数介绍
    Apache Drill 调研学习
    公有云与私有云对比分析报告
    python3 使用libvirt 相关安装
    libvirt虚拟库
    Reveal CocoaPods的使用
    AFNetworking 2.0 使用
  • 原文地址:https://www.cnblogs.com/sharesdk/p/8688533.html
Copyright © 2011-2022 走看看