推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
billion
V2EX  ›  Python

mongoengine 如何使用 xxx[yyy].object()的形式获取数据?

  •  
  •   billion ·
    kingname · Jan 3, 2016 · 3129 views
    This topic created in 3933 days ago, the information mentioned may be changed or developed.

    当我们使用 pymongo 的时候,可以使用下面的方式连接到 example 数据库中的名叫 col 的集合中:

    conn = pymongo.MongoClient()
    db = conn.example
    collection = db.col
    

    当然也可以使用如下的代码,他们的作用是完全一样的。

    dbname = 'example'
    collectionName = 'col'
    conn = pymongo.MongoClient()
    db = conn[dbname]
    connection = db[collectionName]
    

    但是现在我使用 mongoengine, 假设我在数据库中有一个集合叫做 collectionA, 然后在 model.py 文件中有这样一个类:

    class collectionA(Document):
        A=StringField()
        B= StringField()
    

    所以我就可以使用

    import model
    x = model.collectionA.object(A='xxx')
    

    来查询数据

    由于有很多的集合,所以我希望是用

    model[collectionName].object(A='xxx ')
    

    来查询数据,但是我发现 mongoengin 似乎不支持这种方式.

    所以我想请问一下是不是我的用法不对,以及应该如何修改。我确实不想写几十个 if - elif 。感谢!

    2 replies  •  2016-01-03 20:06:05 +08:00
    janxin
        1
    janxin  
       Jan 3, 2016
    是不支持的
    Drifter
        2
    Drifter  
       Jan 3, 2016
    Of course, this is not support.

    为什么要定义 Document ,就是为了将数据库中的 collection 与 python 中定义的 class 映射。
    而 pymongo 可以是因为直接将 collection 取出来作了[{}]这样的基本数据结构。

    你当然需要定义好你这边的 document ,才能让 mongoengine 找到映射的 collection ,再转成对应的 document 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2895 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 11:43 · PVG 19:43 · LAX 04:43 · JFK 07:43
    ♥ Do have faith in what you're doing.