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"]
  • 相关阅读:
    BZOJ1001 BJOI2006 狼抓兔子
    NOI2015 程序自动分析
    高斯消元法
    [POJ] 3666 Making the Grade
    [CODEVS] 2185 最长公共上升子序列
    [模板] LIS
    [CF] 219D Choosing Capital for Treeland
    [POJ] 2823 Sliding Window
    [BZOJ] 1072 [SCOI2007]排列perm
    [POJ] 1094 Sorting It All Out
  • 原文地址:https://www.cnblogs.com/sharesdk/p/8688533.html
Copyright © 2011-2022 走看看