skip to Main Content

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.

2

Answers


  1. 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 🙂

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search