I have recently shifted to MongoDB
and Mongoose
with Node.js
. And I am wrapping my head around it all coming from SQL
.
I have a collection where documents have a similar structure to the following:
{
name: String
rank: Number
}
Sometimes the name
might be the same, but the rank
will always be different.
I would like to remove all duplicates of name
, but retain the object that has the LOWEST rank
.
For instance, if my collection looked like this:
{
name: "name1"
rank: 3
},
{
name: "name1"
rank: 4
},
{
name: "name1"
rank: 2
}
I would like to remove all objects where name
is the same except for:
{
name: "name1"
rank: 2
}
Is this possible to do with mongoose?
2
Answers
Okay, I figured it out using
aggregate
:Here is my approach:
Explanation:
From my point of view your solution would result in many unnecessary calls being made, which would result in a terrible time of execution. My solution exactly contains two steps:
name
the corresponding lowestrank
available.Additional notes:
If not already done, you should probably define an index on the
name
property of your schema for performance reasons.