一个MongoAlchemy的例子

来源:互联网 发布:切纸机无刀后数据 编辑:程序博客网 时间:2024/06/07 00:57


贴出一个MongoAlchemy相关的Demo,或许对某些使用MA但不熟悉其操作的童鞋有些帮助,虽然我已经放弃使用MA了(放弃MongoAlchemy使用MongoEngine,放弃原因具体可以看这里:http://www.oschina.net/question/1040876_135249)

问题有结果了,SO上发了帖子,MA(MongoAlchemy)的作者jeff回答了该问题。

http://stackoverflow.com/questions/20265271/mongoalchemy-query-embedded-documents

大概的意思呢就是mongo不支持查询只返回子文档,但是我们的解决方法就是先拿整个的文档,然后自己处理拿出你要的子文档。

经过这个问题,比较了一下MA和ME(MongoEngine)两个项目,感觉MA不是太靠谱,首先用的人比较少,问题也可能比较多,这次就帮助jeff发现了一个bug,然后更新了一下版本。其次,更新代码的速度比较慢,MA除了这次这个bug以外,上次更新是6个月以前,而ME的最近更新是2个月,3个月,7个月以前,更新频率比较快,还是比较活跃的,而且用的人比较多。因此,决定换ME试试。

例子比较复杂,涉及到嵌套文档的使用,但是mongodb查询子文档,目前必须返回整个文档,然后需要你再在手动获取其子文档。代码如下:

#!/usr/bin/python# -*- coding: utf-8 -*-from flask import Flask from flaskext.mongoalchemy import MongoAlchemyapp = Flask(__name__)app.config['DEBUG'] = Trueapp.config['MONGOALCHEMY_DATABASE'] = 'library'db = MongoAlchemy(app)class Author(db.Document):    name = db.StringField(db_field='NAME')class LBS(db.Document):    LON = db.FloatField(db_field='lon', required=True, allow_none=False)    LAT = db.FloatField(db_field='lat', required=True, allow_none=False)class Book(db.Document):    title = db.StringField()    author = db.DocumentField(Author)    year = db.IntField()    lbs = db.DocumentField(LBS)    gps = db.GeoField(db_field='gps')    LIST = db.ListField(db.StringField('favor'), db_field='list')    SuperList = db.ListField(db.DocumentField(LBS), db_field='SuperList')def test():#    save()#    test_list()#    test_basic()    test_author()#    test_SuperList()def test_author():    items = Book.query.filter({'year':2015}).all()    for item in items:        print dir(item.author)        print 'author', item.author        item.author.name = 'alis'        item.save()        print 'author change to alis', item.author.name        author = item.author        author.name = 'ZT'        author.save()        print 'author change to sam', author.namedef save():    author = Author(name='me')    #author.save()    lbs = LBS(LON=2.333, LAT=3.2222)    gps = [124.305, 132.356]    LIST = ['1', '2', '3']    SuperList = [lbs, lbs]    book = Book(title='title', year=2015, author=author, lbs=lbs, gps=gps, LIST=LIST, SuperList=SuperList)    book.save()def test_SuperList():    items = Book.query.filter({'year':2015}).all()    for item in items:        print dir(item.SuperList)        print 'item.SuperList', item.SuperList        '''        for lbs in item.SuperList:            print 'lbs', lbs            print 'lbs.LON', lbs.LON            lbs.LON = 133.333            #lbs.save()   #不能这样保存,这样保存直接存到lbs表里了            item.SuperList.lbs.save()            print 'lbs.LON', lbs.LON        '''        #保存都保存到了lbs的表里面了,怎么办??????????           '''        for i in range(0, len(item.SuperList)):            item.SuperList[i].LON = 111.11            item.SuperList[i].save()            print 'item.SuperList.lbs.LON', item.SuperList[i].LON            pass        '''        for i in range(0, len(item.SuperList)):            item.SuperList[i].LON = 111.11            item.SuperList[i].save()            print 'item.SuperList.lbs.LON', item.SuperList[i].LON            passdef test_basic():    items = Book.query.filter({'year':2015}).all()    for item in items:        print item.author.name#, item.lbs        print dir(item.LIST)        try:            gps = item.gps            print gps[1]#, item.lbs            print item.author.sname#, 没有sname        except:            print 'error basic'def test_list():    items = Book.query.filter({'year':2015}).all()    for item in items:        print dir(item.LIST)        #print 'before start', item.LIST                item.LIST = ['1', '3', '6']        item.save()        print '1 count:', item.LIST.count('1'), item.LIST        item.LIST.append('7')        item.save()        print 'append ', item.LIST                item.LIST.pop()        item.save()        print 'pop', item.LIST        item.LIST.insert(2, '3')  #loc, text        item.save()        print 'insert', item.LIST        try:            item.LIST.remove('7')  #没有会报错            item.save()            print 'remove', item.LIST        except:            print 'error remove'               item.LIST.reverse()        item.save()        print 'reverse', item.LIST             item.LIST.sort()        item.save()        print 'sort', item.LISTif __name__ == '__main__':    test()