Search code examples
mongodbmongodb-queryaggregation-frameworkaggregateaggregate-functions

filter unique document basis on a particular key lie on document


I am using Mongo aggregate framework, suppose if i am having collection structure like this

{
  {
    _id: ObjectId(123)
    name: john,
    age: 30
  },
  {
    _id: ObjectId(456)
    name: moore,
    age: 45
  },
  {
    _id: ObjectId(789)
    name: carl,
    age: 30
  }
}

I want to get only unique age documents for example, result should look like this

{
  {
    _id: ObjectId(123)
    name: john,
    age: 30
  },
  {
    _id: ObjectId(456)
    name: moore,
    age: 45
  },
}

Above result have removed same age document and taken any single document of them.

How can I perform this set operation on collection on the basis of age, by which I only get unique age document collection using mongo aggregation


Solution

  • db.collection.aggregate([
      {
        $group: {
          _id: "$age",
          firstDocument: {
            $first: "$$ROOT"
          }
        }
      },
      {
        $replaceRoot: {
          "newRoot": "$firstDocument"
        }
      }
    ])
    
    1. $group will retain single document for age. Since, you want to retain the structure of the document, use $$ROOT to assign the whole document to a field.

      The output of this stage will be something like this.

      {
        "_id": 45,
        "firstDocument": {
          "_id": 345,
          "age": 45,
          "name": "moore"
        }
      }
      
    2. $replaceRoot will replace the whole document from previous stage with the one you want. In this case, it is what we assigned to "firstDocument" field.

    MongoPlayground