访问MongoDB和Python中的嵌套项

访问MongoDB和Python中的嵌套项,python,mongodb,pymongo,database,Python,Mongodb,Pymongo,Database,在MongoDB中,我通过Python脚本插入了以下关于夏季柠檬水价格变化的条目: { "_id" : ObjectId('ffffffffffffffffff'), "Drink" : "Lemonade" "Prices per dates" : [ { "Date" : "02-22-2017", "Price" : "5.00" }, { "Da

在MongoDB中,我通过Python脚本插入了以下关于夏季柠檬水价格变化的条目:

{
    "_id" : ObjectId('ffffffffffffffffff'),
    "Drink" : "Lemonade"
    "Prices per dates" : [
        {
            "Date" : "02-22-2017",
            "Price" : "5.00"
        },
        {
            "Date" : "02-21-2017",
            "Price" : "6.00"
        },            
        {
            "Date" : "02-20-2017",
            "Price" : "7.00"
        }
     ]
}
我只想摘录价格并打印:

五点 6 7点

我在StackOverflow上读了这篇文章:

不可能做我想做的事吗?还是我误解了这个问题的答案


然而,如果有可能做到这一点,我将如何做到?有没有更好的方法来格式化我的数据库,使我的工作更容易?很抱歉,如果这是一个非常基本的问题,我最近开始学习如何处理所有这些问题。

正如链接的答案所说,MongoDB将始终返回完整文档,但您可以轻松地从中提取价格:

prices = [p["Price"] for p in doc["Prices per dates"]]

其中doc是从数据库返回的dict。

上述答案有效。作为将来的参考,这是我的最终解决方案:

for i in [p["Price"] for p in collection.find_one({"Drink":"Lemonade"}["Prices per dates"]]:
    print i
输出:

5.00
6.00
7.00