Answer the question
In order to leave comments, you need to log in
How to select only unique values from MongoDB?
Good afternoon!
Let's say we have a collection like this:
[{
"task": 1,
"creator": 1,
"progress" : 0,
}, {
"task": 1,
"creator": 1,
"progress" : 0.3,
}, {
"task": 1,
"creator": 1,
"progress" : 0.7,
}, {
"task": 2,
"creator": 1,
"progress" : 0.1,
}, {
"task": 2,
"creator": 1,
"progress" : 0.5,
}, {
"task": 2,
"creator": 1,
"progress" : 0.9,
}]
[{
"task": 1,
"creator": 1,
"progress" : 0.7,
}, {
"task": 2,
"creator": 1,
"progress" : 0.9,
}]
const uniqTasks = Task.find({
creator: 1
})
.distinct('task')
.exec();
Promise.all(uniqTasks.map(task) => {
return Task.findOne({
creator: 1,
task: task
})
.sort({_id: -1})
.exec();
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question