我在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上的这篇文章: 访问MongoDB中的嵌套对象
难道不可能做我想要的吗? 还是我误解了这个问题的答案?
但是,如果可以这样做,我该怎么做? 有没有更好的方法来格式化我的数据库,这将使我的工作更轻松? 对不起,如果这是一个非常基本的问题,我最近开始学习如何使用这一切。
I have the following entry in MongoDB about changing prices of lemonade during the summer that I inserted through a Python script:
{ "_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" } ] }I would like to extract just the prices and print:
5.00 6.00 7.00
I was reading this post on StackOverflow: Accessing Nested Objects in MongoDB
Is it not possible to do what I want? Or did I misinterpret the answer to that question?
However, If it is possible to do this, how would I do it? And is there a better way to format my database that would make my job easier? I'm sorry if this is a very basic question, I started learning how to work with all of this recently.
最满意答案
正如链接的答案所说,MongoDB将始终返回完整的文档,但您可以轻松地从中提取价格:
prices = [p["Price"] for p in doc["Prices per dates"]]doc是从数据库返回的dict。
As that linked answer says, MongoDB will always return the full document, but you can easily extract the prices from that:
prices = [p["Price"] for p in doc["Prices per dates"]]where doc is the dict returned from the database.
更多推荐
发布评论