Search code examples
pythonmongodbpymongodatabase

Accessing Nested Entries in MongoDB and Python


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.


Solution

  • 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.