How to find documents with unique values in MongoDB?

回眸只為那壹抹淺笑 提交于 2019-12-25 03:33:25

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/30655040/how-to-find-documents-with-unique-values-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!