I have a collection with several documents in it of jobs to process using another system. I look up 5 objects from this table like this:
Work.find({status: 'new'})
.sort({priority: 'desc'})
.limit(5)
.exec(function (err, work){})
There is another field on these documents which determines that only one job with a given unique value can be ran at the same time.
For example these 3 jobs:
{uniqueVal: 1, priority: 1, type: "scrape", status:"new"}
{uniqueVal: 1, priority: 1, type: "scrape", status:"new"}
{uniqueVal: 2, priority: 1, type: "scrape", status:"new"}
There are 2 records with the uniqueVal of 1. Is there anything I can do to only pull one record with the value 1?
Note: These values are not predetermined values like in the example, they are ObjectIds of other documents.
I've looked into Distinct(), but it seems like it only returns the actual unique values, not the documents themselves.
I think the best choice is to use aggregation.
You can $group by uniqueVal http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group
And use $first for the other values http://docs.mongodb.org/manual/reference/operator/aggregation/first/#grp._S_first