访问MongoDB和Python中的嵌套条目

时间:2017-02-25 20:03:32

标签: python mongodb pymongo database

我在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"
        }
     ]
}

我想提取价格并打印:

5.00 6.00 7.00

我正在阅读StackOverflow上的这篇文章:Accessing Nested Objects in MongoDB

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

但是,如果可以这样做,我该怎么做?有没有更好的方法来格式化我的数据库,这将使我的工作更轻松?对不起,如果这是一个非常基本的问题,我最近开始学习如何使用这一切。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

上面的答案奏效了。为了将来参考,这是我的最终解决方案:

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

输出:

5.00
6.00
7.00