使用 Python 显示 Mongo 数据库中的嵌入数据
Displaying embedded data in Mongo DB with Python
我正在使用 Flask 和 Mongo DB 开发一个项目,我想显示一些嵌入式文档。我并没有真正收到错误消息,但数据没有显示我想要的方式。目前,我的文档如下所示:
{ "_id" : ObjectId("590639009103ad05fd8555dc"),
"comments" : [ { "comment" :
"Hello World" } ],
"age" : 23,
"name" : "Mike" }
现在,我想显示将显示个人所说的姓名和评论的数据。我想要这样的东西:Mike,说了以下内容:'Hello World'
我的代码如下所示:
thoughts = person.show()
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"])
show() 方法如下所示:
def show(self):
thoughts = self.db.people.find()
return thoughts
现在大部分情况下几乎一切都按照我想要的方式运行。当我 运行 我的代码时,我得到了这个:
迈克说了以下内容:{'comment': 'Hello World'}
我需要做的是深入挖掘嵌入文档以显示:
Mike,说了以下内容:'Hello World'
我试过以下方法:
for thought in thoughts:
print(thought["name"], "says the following:",
thought["comments.comment"])
这让我收到以下错误消息:KeyError: 'comments.comment'
然后我尝试了以下操作:
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"]
["comment"])
这给了我以下错误:
类型错误:列表索引必须是整数,而不是 str
因此,我有点卡住了如何拉出每条评论。任何帮助,将不胜感激。
thought["comments"]
是一个字典列表。您想要列表中第一项的 comment
字段,因此:
print(thought["comments"][0]["comment"])
我正在使用 Flask 和 Mongo DB 开发一个项目,我想显示一些嵌入式文档。我并没有真正收到错误消息,但数据没有显示我想要的方式。目前,我的文档如下所示:
{ "_id" : ObjectId("590639009103ad05fd8555dc"),
"comments" : [ { "comment" :
"Hello World" } ],
"age" : 23,
"name" : "Mike" }
现在,我想显示将显示个人所说的姓名和评论的数据。我想要这样的东西:Mike,说了以下内容:'Hello World'
我的代码如下所示:
thoughts = person.show()
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"])
show() 方法如下所示:
def show(self):
thoughts = self.db.people.find()
return thoughts
现在大部分情况下几乎一切都按照我想要的方式运行。当我 运行 我的代码时,我得到了这个: 迈克说了以下内容:{'comment': 'Hello World'}
我需要做的是深入挖掘嵌入文档以显示:
Mike,说了以下内容:'Hello World'
我试过以下方法:
for thought in thoughts:
print(thought["name"], "says the following:",
thought["comments.comment"])
这让我收到以下错误消息:KeyError: 'comments.comment'
然后我尝试了以下操作:
for thought in thoughts:
print(thought["name"], "says the following:", thought["comments"]
["comment"])
这给了我以下错误: 类型错误:列表索引必须是整数,而不是 str
因此,我有点卡住了如何拉出每条评论。任何帮助,将不胜感激。
thought["comments"]
是一个字典列表。您想要列表中第一项的 comment
字段,因此:
print(thought["comments"][0]["comment"])