user471011
user471011

Reputation: 7374

Mongo DB: How to get original Document after aggregation stage $group?

Documents that I have:

[
  {
    "_id": 1,
    "entity": "Category",
    "property": "name",
    "changed": "2021-08-30"
  },
  {
    "_id": 2,
    "entity": "Category",
    "property": "name",
    "changed": "2020-08-31"
  },
  {
    "_id": 3,
    "entity": "Category",
    "property": "description",
    "changed": "2020-08-29"
  },
  {
    "_id": 4,
    "entity": "Category",
    "property": "description",
    "changed": "2020-08-30"
  },
  {
    "_id": 5,
    "entity": "Category",
    "property": "description",
    "changed": "2020-08-31"
  }
]

I am trying to execute the following query:

db.collection.aggregate([
  {
    $group: {
      _id: {
        property: "$property"
      },
      lastChanged: {
        $max: "$changed"
      }
    }
  }
])

to find the Documents per each unique property that was last modified

The query output is:

[
  {
    "_id": {
      "property": "name"
    },
    "lastChanged": "2021-08-30"
  },
  {
    "_id": {
      "property": "description"
    },
    "lastChanged": "2020-08-31"
  }
]

The problem that I have, it is how to return original Documents not just some custom query output?

Upvotes: 3

Views: 1116

Answers (2)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59503

Use this one:

db.collection.aggregate([
   {
      $group: {
         _id: { property: "$property" },
         lastChanged: { $max: "$changed" },
         data: { $push: "$$ROOT" }
      }
   },
   {
      $set: {
         data: {
            $filter: {
               input: "$data",
               cond: { $eq: ["$$this.changed", "$lastChanged"] }
            }
         }
      }
   }
])

Then in your result you have a field data with all your documents.

Upvotes: 4

varman
varman

Reputation: 8894

You can achieve using sort

db.collection.aggregate([
  {
    $sort: {
      changed: -1
    }
  },
  {
    $group: {
      _id: {
        property: "$property"
      },
      data: {
        $first: "$$ROOT"
      }
    }
  }
])

Working Mongo playground

Upvotes: 0

Related Questions