Search code examples
pythonarraysmongodblistpymongo

using pymongo,I want to retrieve only values in hint's subject from hints array if the hint type is free&active and then list the values into a list


As title suggests, I have this document structure:

{
   "_id":ObjectId("61e53553ac31665894ebf6bc"),
   "questionID":"8",
   "questionContent":"find it",
   "questoinAnswer":"it's here",
   "questionStatus":"active",
   "questionImage":"some image",
   "hints":[
      {
         "hintID":"1",
         "hintSubject":"in you pucket",
         "hintContent":"bla bla bla",
         "hintType":"private",
         "hintStatus":"Active",
         "time":"2022-01-23 11:02:41.976391"
      },
      {
         "hintID":"2",
         "hintSubject":"red sea",
         "hintContent":"bla bla bla",
         "hintMedia":"some media",
         "hintType":"puplic",
         "hintStatus":"Active",
         "time":"2022-01-23 11:05:47.567226"
      }
   ]
}

I want to retrieve only the values of hintSubject if the hintType is free and hintStatus is active and put it into a list


Solution

  • Use the below aggregation query where list of hintSubject is stored in hintSubject key in root dictionary key.

    from pymongo import MongoClient
    
    
    c = MongoClient()
    db = c["db_name"]
    col = db["sample_collection"]
    
    for x in col.aggregate([
      {
        "$addFields": {
          "hintSubject": {
            "$reduce": {
              "input": "$hints",
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  {
                    "$cond": {
                      "if": {
                        "$and": [
                          {
                            "$eq": [
                              "$$this.hintType",
                              "free"
                            ]
                          },
                          {
                            "$eq": [
                              "$$this.hintStatus",
                              "Active"
                            ]
                          },
                          
                        ]
                      },
                      "then": [
                        "$$this.hintSubject"
                      ],
                      "else": [],
                      
                    },
                    
                  },
                  
                ],
                
              },
              
            },
            
          }
        }
      }
    ])
    
    print(x["hintSubject"])
    

    Mongo Playground Sample Execution