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
first, you want to update mongoose v3 or up
the solution is to use the distinct function
I hope it will help you 🙂
Use
$first
to pick a document in$group
stage. Then do some wrangling with$unwind
and$replaceRoot
to retrieve the document.Here is the Mongo Playground for your reference.