1

I'm attempting to extract the highest value from an child Array within Object, that is within a parent Array - in a single MongoDB document.

The child Array is called data contained within the list parent Array, where i'm trying to extract the highest number, when compared to the rest of the same values.

I've tried using $Group and $max (example below) among other things - however not getting much success. - I am getting an array returned with all the number values: [2,3]

How do I search through the list Array and data Array to return the highest number?

Expected Output for the below example: {output: 3}

Example in MongoPlayground: https://mongoplayground.net/p/qw9Kz_WVYiS

Mongo DB Setup and Documents

db={
  "groups": [
    {
      "_id": ObjectId("602ed22af42c404096407dda"),
      "groupName": "Name"
    }
  ],
  "inventory": [
    {
      "_id": ObjectId("602ed22af42c404096407ddc"),
      "linkedGroup": ObjectId("602ed22af42c404096407dda"),
      "list": [
        {
          "_id": ObjectId("602eeb0621a11045638b7082"),
          "data": {
            "number": 2
          },
          
        },
        {
          "_id": ObjectId("602eec75c37147459ed7b12c"),
          "data": {
            "number": 3
          }
        }
      ]
    }
  ]
}

Query

db.groups.aggregate([
  {
    "$lookup": {
      "from": "inventory",
      "localField": "_id",
      "foreignField": "linkedGroup",
      "as": "inventory_links"
    }
  },
  {
    $group: {
      _id: 1,
      output: {
        $max: "$inventory_links.list.data.number"
      },
      
    },
    
  }
])

1 Answer 1

1

$reduce to find the maximum. With your query, you can add other stages,

{
    $addFields: {
      _id: 1,
      inventory_links: {"$arrayElemAt": ["$inventory_links",0]}
    }
},
{
    $project: {
      output: {
        $reduce: {
          input: "$inventory_links.list",
          initialValue: 0,
          in: {
            $cond: [
              {$gte: [ "$$this.data.number","$$value"]},
              "$$this.data.number",
              "$$value"
            ]
          }
        }
      }
    }
}

Working 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.