0

I have a document structures like this :

    {
      "_id": xxxxx,
      "Name": "John Doe",
      "Grades":[
        {
        "Physics":89,
        },
        {
          "Math":45
        },
        {
          "Chemistry":57
        }
      ]
    }

I would like to project grades as an array of only the subjects that have over 60.

I tried this but this didn't work:

$arrayElemAt: [{ $objectToArray: { $gte: ['$hhEthGrp',60] } }, 0]

1 Answer 1

1

You definitely need $objectToArray to access a values for unknown keys but you also need $filter for outer array and $anyElementTrue along with $map to determine where there's any value for unknown key which has value over 60:

db.collection.aggregate([
    {
        $addFields: {
            Grades: {
                $filter: {
                    input: "$Grades",
                    cond: {
                        $let: {
                            vars: { kv: { $objectToArray: "$$this" } }
                            in: {
                                $anyElementTrue: {
                                    $map: {
                                        input: "$$kv.v",
                                        in: {
                                            $gt: [ "$$this", 60 ]
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.