Search code examples
mongodbmongodb-querypymongo

I am having difficulty in querying the follwing nested document using pymongo


If these are the following nested documents

[
  {
    "_id": 5,
    "name": "Wilburn Spiess",
    "scores": [
      {
        "score": 44.87186330181261,
        "type": "exam"
      },
      {
        "score": 25.72395114668016,
        "type": "quiz"
      },
      {
        "score": 63.42288310628662,
        "type": "homework"
      }
    ]
  },
  {
    "_id": 6,
    "name": "Jenette Flanders",
    "scores": [
      {
        "score": 37.32285459166097,
        "type": "exam"
      },
      {
        "score": 28.32634976913737,
        "type": "quiz"
      },
      {
        "score": 81.57115318686338,
        "type": "homework"
      }
    ]
  },
  {
    "_id": 7,
    "name": "Salena Olmos",
    "scores": [
      {
        "score": 90.37826509157176,
        "type": "exam"
      },
      {
        "score": 42.48780666956811,
        "type": "quiz"
      },
      {
        "score": 96.52986171633331,
        "type": "homework"
      }
    ]
  }
]

I need to access the score part 'type' = exam.

Can somebody help me with this?


Solution

  • If you're asking for a python program to access the score, you can print them out like:

    collection = mongo_connection['db']['collection']
    documents = collection.find({})
    for doc in documents:
        for score in doc['scores']:
            if score['type'] == 'exam':
                print(f'Score: {score["score"]}')
    

    If you are trying to retrieve only the scores and ignore the rest, I'd do an $unwind on the scores, $match on the type, and then project the fields you want (or not).

    db.test.aggregate([
        {
            $unwind: '$scores'
        },
        {
            $match: {
                'scores.type': 'exam'
            }
        },
        {
            $project: {
                'name': '$name',
                'score': '$scores.score'
            }
        }
    ])
    

    This would output:

    {
        "_id" : 5,
        "name" : "Wilburn Spiess",
        "score" : 44.8718633018126
    },
    {
        "_id" : 6,
        "name" : "Jenette Flanders",
        "score" : 37.322854591661
    },
    {
        "_id" : 7,
        "name" : "Salena Olmos",
        "score" : 90.3782650915718
    }