zoukankan      html  css  js  c++  java
  • MongoDB与python 交互

    一、安装pymongo

    注意 :当同时安装了python2和python3,为区分两者的pip,分别取名为pip2和pip3。

    推荐:https://www.cnblogs.com/thunderLL/p/6643022.html

    二、MongoDB与python 交互

    2.1、打开黑屏终端,启动mongodb服务,运行mongo

    # encoding=utf8
    from pymongo import MongoClient
    from bson.objectid import ObjectId
    import pymongo
    
    # 连接服务器
    conn = MongoClient("localhost", 27017)
    
    # 连接数据库
    db = conn.text
    
    # 获得集合
    collection = db.sub
    
    # 添加数据
    collection.insert(
        {'name': 'dd', 'gender': 1, 'math': 30, 'chinese': 50}
    )
    # 查询文档
    # res = collection.find()
    # 查询部分文档
    '''
    res = collection.find({"math": {"$gt": 60}})
    for row in res:
        print(row)
        print(type(row))
    '''
    # 统计查询
    '''
    res = collection.find({"math": {"$gt": 60}}).count()
    print(res)
    '''
    # 根据id 查询
    '''
    res = collection.find({"_id":ObjectId('5b927e096e92f1c1d53e548f')})
    print(res[0])
    '''
    # 排序
    '''
    res = collection.find().sort("math")  # 升序
    res = collection.find().sort("math", pymongo.DESCENDING)
    for row in res:
        print(row)
    '''
    # 分页查询
    '''
    res = collection.find().skip(3).limit(4)
    for row in res:
        print(row)
    '''
    
    # 更新文档
    '''
    collection.update({"name": "bbb"}, {"$set": {"math": 100}})
    '''
    #删除
    '''
    collection.remove({"name": "dd"})
    '''
    
    # 断开
    conn.close()
    mongodb.py

    三、MongoEngine

    PyMongo是将MongoDB API包装到Python中并提供传入和传出JSON的低级驱动程序。

    MongoEngine或其他类似MongoKit的层将您基于MongoDB的数据映射到类似于本机Python数据库驱动程序+ SQLAlchemy作为ORM的对象。

    https://stackoverflow.com/questions/5712857/pymongo-vs-mongoengine-for-django

  • 相关阅读:
    hdu 3074 Multiply game
    uva 10717 Mint
    uva 10128 Queue
    uva 10673 Play with Floor and Ceil
    hdu 1754 I Hate It
    hdu 1166 敌兵布阵
    uva 10079 Pizza Cutting
    费波那列素数
    uva 10236 The Fibonacci Primes
    hdu 1698 Just a Hook
  • 原文地址:https://www.cnblogs.com/Mint-diary/p/9608397.html
Copyright © 2011-2022 走看看