【问题标题】:MongoDB Flask and pymongoMongoDB 烧瓶和 pymongo
【发布时间】:2013-11-24 21:19:06
【问题描述】:


我尝试使用 python 框架 Flask 和 MongoDB 编写一个 webapp,使用 pymongo 驱动程序。
我需要获得管理员视图,以便能够在线编辑数据,

集合的结构:

db.skills.insert({ "rubric": rubric, "head": title, "body": content })

(如果值为

在控制器中,我通过创建 dict 列表将数据发送到视图:

def skList():
    liste, keys, value = [], [], []
# iterate over the collection to get 2 list of all keys and values.
    for row in db.skills.find():
        keys.append(row.keys())
        value.append(row.values())
# merge the 2 lists.
    zipped = zip(keys, value)
# finally create a list of dict containing each row of my db
    for x, y in zipped:
        liste.append(dict(zip(x, y)))
    return liste

结果是这样的:

liste = [ {_id:ObjectId('89878979879'), 'rubric':'Python', 'body': 'truc'}, {_id:ObjectId('876876899'), 'rubric':'chose', 'head':'blabla', 'body':'foo'} ]

在我看来,我遍历并显示正常!
我还可以编辑/删除每个字段,或删除文档。

当我开始从视图中添加数据时出现了我的问题:

有时,从视图中添加的下一个文档是在集合中间插入的,因此顺序不固定,
从 mongo shell 追加相同的内容。

我在这里找到了解释:
https://groups.google.com/d/msg/mongodb-user/B5jU0uyGhh8/i3LacXcXKDwJ

所以我必须处理我不希望文档由视图显示并且不知道如何执行此操作的顺序:p

有人可以提出解决方案,也许我应该使用不同的模式?

【问题讨论】:

标签: python mongodb flask pymongo


【解决方案1】:

有一种解决方案可以遍历 Mongo 集合并返回按每个文档的“索引”字段排序的 dict 列表:

def collecList(collection):
    liste, keys, value = [], [], []
    for row in collection.find().sort("index"):
        keys.append(row.keys())
        value.append(row.values())
    zipped = zip(keys, value)
    for x, y in zipped:
         liste.append(dict(zip(x, y)))
    return liste

【讨论】:

  • 它和list(collection.find().sort("index"))有什么区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2019-11-24
  • 2018-10-10
  • 2018-03-26
相关资源
最近更新 更多