简体   繁体   中英

How to retrieve sub documents in a Array from mongoDB using python script

I am quite new to python and mongoDB and need to achieve this task.

I have a collection containing documents similar to the sample below.

{
        "_id" : 1900123,
        "name" : "AAAAA BBBB",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 44.51211101958831
                },
                {
                        "type" : "quiz",
                        "score" : 0.6578497966368002
                },
                {
                        "type" : "projectwork",
                        "score" : 93.36341655949683
                },
                {
                        "type" : "projectwork",
                        "score" : 49.43132782777443
                }
        ]
}

I am trying to read this collection in a python script. I am unable to retrieve the score from the sub document

cursor = students.find()

for doc in cursor:
        score1=doc["scores.2.score"];
        print("score1=",score1);

I am trying to find the lowest score for project work for each student, but i am unable to retrieve the score using index "scores.2.score".

Need some help to understand the retrieval method.

pymongo's find method internally uses db.collections.find which actually returns the cursor. When you iterate the cursor, you will get the individual documents. The documents returned will be represented in Python as a dictionary. So, in this case, doc is a dictionary. When you do

doc["scores.2.score"]

you are trying to fetch an item corresponding to the key scores.2.score in the doc dictionary. But as you see from the structure shown in the question, there is no such key called scores.2.score . Actually, when you do

doc["scores"]

you will get

[
    {
        "type": "exam",
        "score": 44.51211101958831
    },
    {
        "type": "quiz",
        "score": 0.6578497966368002
    },
    {
        "type": "projectwork",
        "score": 93.36341655949683
    },
    {
        "type": "projectwork",
        "score": 49.43132782777443
    }
]

which is a list and to get the second element from it, you will do

doc["scores"][2]

which will give you the dictionary

    {
        "type": "projectwork",
        "score": 93.36341655949683
    }

and to access score in it, you will do

doc["scores"][2]["score"]

and that will actually give you

93.36341655949683.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM