访问MongoDB和Python中的嵌套条目(Accessing Nested Entries in MongoDB and Python)

编程入门 行业动态 更新时间:2024-10-23 15:22:48
访问MongoDB和Python中的嵌套条目(Accessing Nested Entries in MongoDB and Python)

我在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.

更多推荐

本文发布于:2023-08-05 19:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   条目   Python   MongoDB   Nested

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!