0

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.

Community
  • 1
  • 1
ss1111
  • 239
  • 1
  • 9
  • 20

2 Answers2

1

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

The answer above worked. For future reference, this was my final solution:

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

Output:

5.00
6.00
7.00
ss1111
  • 239
  • 1
  • 9
  • 20