mongoengine在python中的使用

# /usr/bin/python
# encoding: utf-8
# Author: masako


from mongoengine import *

host ='127.0.0.1'
port = 27017
user = 'test'
password = 'test123'
db_name = 'test'
collection = 'mytest'
db_url = 'mongodb://test:test123@127.0.0.1:27017/test'

connect(db=db_name, host=host, port=port, username=user, password=password)
# connect(db_name, host=db_url)
# db_name 是数据库的名字, connect()的默认第一个参数
# host是主机名.可以直接传数据库链接
# 授权可使用'username'  和 'password'参数,或者直接写在url之中


class Users(Document):      # 继承document,类名为集合名,与数据库中集合名字相同,不分大小写
    name = StringField()    # 字段,与数据库内相应集合的字段相同
    age = StringField()


users = Users.objects.all() # 取出users集合中所有数据

for u in users:
    print u.name

 

  搞明白了比较困惑的一点,就是数据的联系在哪里.若使用pymongo,会有一个connect对象,用以操作数据库.

 在mongo engine中,Document对象就是connect链接到的数据库,只需要继承它,就可以进行相应操作.而在使用时,若已创建了要使用的数据库,则类名和属性名都要一一对应来使用.

  区别与pymongo,mongoengine的思想是ORM,更贴近适用性,直接面向对象.而pymongo则更贴近数据库,一旦链接上,就像直接使用数据库一样简单.

posted @ 2018-03-05 11:36  Masako  阅读(381)  评论(0编辑  收藏  举报