2

I have a MongoDB collection containing elements like this:

{
    "name": "test",
    "instances": [
        {
            "year": 2015
        },
        {
            "year": 2016
        },
    ]
}

How can I get the minimum and maximum value for year within the document named test? E.g. I want to aggregate all documents inside that array, but I can't find the syntax for that. Thanks in advance!

LukeLR
  • 1,129
  • 1
  • 14
  • 27

2 Answers2

2

Both $min and $max takes an array as a parameter and in your case path instances.year returns an array so your query can look like below:

db.col.aggregate([
    {
        $match: { name: "test" }
    },
    {
        $project: {
            minYear: { $min: "$instances.year" },
            maxYear: { $max: "$instances.year" }
        }
    }
])
mickl
  • 48,568
  • 9
  • 60
  • 89
1

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "maxYear": {
      "$arrayElemAt": [
        "$instances",
        {
          "$indexOfArray": [
            "$instances.year",
            { "$max": "$instances.year" }
          ]
        }
      ]
    },
    "minYear": {
      "$arrayElemAt": [
        "$instances",
        {
          "$indexOfArray": [
            "$instances.year",
            { "$min": "$instances.year" }
          ]
        }
      ]
    }
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132