当前位置: 主页 > 日志 > Python >

在Python中使用MongoEngine操作MongoDB

我使用了一个名为MongoEngine的封装API,它和Django的ORM很类似。

感觉安装和使用都很方便。

关于MongoEngine的更多资料可以看这里:http://mongoengine.org/

User Guide http://readthedocs.org/docs/mongoengine-odm/en/latest/guide/index.html

一段测试代码:

# coding: utf-8
# See more about mongoengine here http://mongoengine.org/
# User Guide http://readthedocs.org/docs/mongoengine-odm/en/latest/guide/index.html

from mongoengine import *

class shop_locations(Document):
    shop_id = IntField()
    shop_name = StringField()
    activated = StringField()
    address = StringField()
    category = StringField()
    lng = StringField()
    lat = StringField()
    location = ListField(FloatField())

if __name__ == '__main__':
    # 连接shop_locations库
    connect('shop_locations')
    # shop_id为1的记录是否存在,不存在则创建,存在则打印出地址
    try:
        sl = shop_locations.objects.get(shop_id=1)
    except shop_locations.DoesNotExist:
        sl = shop_locations()
        sl.shop_id = 1
        sl.shop_name = 'Starbucks'
        sl.activated = 'Y'
        sl.address = '921, Whitehorse Road, Box Hill,Melbourne,3128, Victoria, Australia'
        sl.category = 'cafe'
        sl.lng = '145.1225427'
        sl.lat = '-37.8181463'
        sl.location = [145.1225427, -37.8181463]
        sl.save()
    else:
        print sl.address

程序运行后,查看一下MongoDB:

[日志信息]

该日志于 2012-04-26 11:37 由 redice 发表在 redice's Blog ,你除了可以发表评论外,还可以转载 “在Python中使用MongoEngine操作MongoDB” 日志到你的网站或博客,但是请保留源地址及作者信息,谢谢!!    (尊重他人劳动,你我共同努力)
   
验证(必填):   点击我更换验证码

redice's Blog  is powered by DedeCms |  Theme by Monkeii.Lee |  网站地图 |  本服务器由西安鲲之鹏网络信息技术有限公司友情提供

返回顶部