Home > Blockchain >  MongoDb Aggregate Add Field with Multiple Condition Query Error
MongoDb Aggregate Add Field with Multiple Condition Query Error

Time:11-10

I am trying to execute this Mongodb query using python

pipeline = [{"$addFields": {"Status": {"$cond": [{"$and": [{"$gte": ["scores.0.score",40.0]},{"$gte": ["scores.1.score",40.0]},{"$gte": ["scores.2.score",40.0]}]},"Pass","Fail"]}}}]

Student_Status = list(db.Student_Collection.aggregate(pipeline))

enter image description here

what i am trying to do is to create a new field called "STATUS" where the student who scored more than 40 marks in all 3 categories their status will be updated to "Pass", Rest of the students their status will be updated to "Fail"

But in this code the All Student "Status" Field is updating to "Pass", Student who failed in 1 category their status is not updating to "Fail"

CodePudding user response:

Here's one way you could do it and "future proof" the pass criteria in case different "type"s have individual passing scores.

db.collection.aggregate([
  {
    "$set": {
      "allPass": {
        "$reduce": {
          "input": "$scores",
          "initialValue": true,
          "in": {
            "$switch": {
              "branches": [
                {
                  "case": {"$eq": ["$$this.type", "exam"]},
                  "then": {"$and": ["$$value", {"$gte": ["$$this.score", 40.0]}]}
                },
                {
                  "case": {"$eq": ["$$this.type", "quiz"]},
                  "then": {"$and": ["$$value", {"$gte": ["$$this.score", 40.0]}]}
                },
                {
                  "case": {"$eq": ["$$this.type", "homework"]},
                  "then": {"$and": ["$$value", {"$gte": ["$$this.score", 40.0]}]}
                }
              ]
            }
          }
        }
      }
    }
  },
  {
    "$set": {
      "Status": {"$cond": ["$allPass", "Pass","Fail"]},
      "allPass": "$$REMOVE"
    }
  }
])

Try it on mongoplayground.net.

  • Related