H
H
HoHsi2016-05-28 10:30:04
NoSQL
HoHsi, 2016-05-28 10:30:04

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,
}]

those. we have a user ID, a task ID and its progress.
The task is as follows: select only the latest (unique) progress for each task, for a specific user.
Those. the output should be:
[{
  "task":       1,
  "creator":    1,
  "progress" :  0.7,
}, {
  "task":       2,
  "creator":    1,
  "progress" :  0.9,
}]

Now I tried to do
const uniqTasks = Task.find({
  creator:  1
})
  .distinct('task')
  .exec();

This gives us a dictionary, and then findOne + sort({_id: -1}) in Promise.all.
Promise.all(uniqTasks.map(task) => {
  return Task.findOne({
    creator:  1,
    task: task
  })
    .sort({_id: -1})
    .exec();
});

As you understand, these are N parallel queries to the database, that is, to put it mildly, shit code. How can these queries be aggregated so that the output has the same result?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2016-05-28
@lega

Do not store duplicates and that's all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question