LukeLR
LukeLR

Reputation: 1179

MongoDB aggregate array documents

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!

Upvotes: 2

Views: 88

Answers (2)

Ashh
Ashh

Reputation: 46451

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

Upvotes: 1

mickl
mickl

Reputation: 49945

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

Upvotes: 2

Related Questions