Python之mongodb操作

1.安装驱动pymongo

 输入命令:pip install pymongo

2.直接使用驱动

#encoding=utf-8
from pymongo import MongoClient
client = MongoClient('127.0.0.1', 27017)
db = client["Collections"]#数据库名
table=db['user']#表名
table.insert({'id':'1','name':'cnki'})

3.ORM框架——flask-mongoengine

输入命令:pip install flask-mongoengine

#encoding=utf-8
from flask import Flask
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'Collections',
    'host': '127.0.0.1',
    'port': 27017
}
db = MongoEngine(app)

class User(db.Document):
    email = db.StringField(required=True)
    first_name = db.StringField(max_length=50)
    last_name = db.StringField(max_length=50)

def __init__(self,email,first_name,last_name):
        self.email=email
        self.first_name=first_name
        self.last_name=last_name

ussr=User(email='123456@qq.com',first_name='二哈',last_name='哈士奇')
ussr.save()

  

posted @ 2016-07-21 22:50  ~沐风  阅读(1907)  评论(0编辑  收藏  举报