Search code examples
pythonmongodblistaggregate-functionskey-value

How to retrive a values in the document as key in MongoDB Python


How can I retrieve a value in the MongoDB document as a Key in the result? I have the following sample document.

[
  {"student_id" : "ABC", "class_id" : 2, 
   "sub" : "phy",
   "scores" : [ 
      { "type" : "exam", "score" : 57.92947112575566 }, 
      { "type" : "quiz", "score" : 21.24542588206755 }, 
      { "type" : "homework", "score" : 68.19567810587429 }, 
      { "type" : "homework", "score" : 67.95019716560351 },
      { "type" : "homework", "score" : 18.81037253352722 } 
    ]
  },
  {"student_id" : "ABC", "class_id" : 28, 
   "sub" : "che",
   "scores" : [ 
      { "type" : "exam", "score" : 39.17749400402234 },
      { "type" : "quiz", "score" : 78.44172815491468 },
      { "type" : "homework", "score" : 20.81782269075502 },
      { "type" : "homework", "score" : 70.44520452408949 },
      { "type" : "homework", "score" : 50.66616327819226 },
      { "type" : "homework", "score" : 53.84983118363991 } 
    ] 
  }
]

I want to retrieve the output as class_id:type format. ie,

[{'2': 'exam'}, {'2': 'quiz'},..] 

I tried the following query:

list(db.student.aggregate([{"$project":{"class_id":1,"type":2,"_id":0}}]))

But I am getting as:

[{'class_id': '2', 'type': 'exam'}, {'class_id': '2', 'cuisine': 'quiz'},..]

Can anyone please help?


Solution

  • EDIT: this is a simpler solution;

    db.collection.aggregate([
      {$project: {res: [{k: "$student_id", v: "$sub"}], _id: 0}},
      {$replaceRoot: {newRoot: {$arrayToObject: "$res"}}}
    ])
    

    See how it works on the playground example