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!

1
  • umm, yeah, you're probably right. I'll update that! Commented Feb 2, 2019 at 12:35

2 Answers 2

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" }
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

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" }
          ]
        }
      ]
    }
  }}
])

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.