Home > Enterprise >  Using Mongo Aggregation to Get Distinct Values Based on Field
Using Mongo Aggregation to Get Distinct Values Based on Field

Time:09-01

So I have a collection called Cars that have some fields that are the same, but I want to be able to only get one of the documents based on that field.

[
  {
    _id:'12345',
    model:'Honda'
  },
  {
    _id:'12346',
    model:'Honda'
  },
  {
    _id:'12347',
    model:'Honda'
  },
  {
    _id:'12348',
    model:'Toyota'
  },
  {
    _id:'12349',
    model:'Volkswagen'
  },
  {
    _id:'12349',
    model:'Volkswagen'
  },
]

So here, I want to be able to get the distinct document based on the model field. I just want one document per model field.

CodePudding user response:

first, you want to update mongoose v3 or up

the solution is to use the distinct function

Cars.find().distinct('model', function(error, models) {});

I hope it will help you :)

CodePudding user response:

Use $first to pick a document in $group stage. Then do some wrangling with $unwind and $replaceRoot to retrieve the document.

db.collection.aggregate([
  {
    $group: {
      _id: "$model",
      doc: {
        $first: "$$ROOT"
      }
    }
  },
  {
    "$unwind": "$doc"
  },
  {
    "$replaceRoot": {
      "newRoot": "$doc"
    }
  }
])

Here is the Mongo Playground for your reference.

  • Related