如何在MongoDB中查找具有唯一值的文档? [英] How to find documents with unique values in MongoDB?
问题描述
我有一个集合,其中包含几个要使用其他系统处理的作业文件.我从此表中查找5个对象,如下所示:
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.
例如,这3个工作:
{uniqueVal: 1, priority: 1, type: "scrape", status:"new"}
{uniqueVal: 1, priority: 1, type: "scrape", status:"new"}
{uniqueVal: 2, priority: 1, type: "scrape", status:"new"}
有2条记录的uniqueVal为1.我能做些什么,只提取一条值为1的记录?
There are 2 records with the uniqueVal of 1. Is there anything I can do to only pull one record with the value 1?
注意:这些值不是示例中的预定值,它们是其他文档的ObjectId.
Note: These values are not predetermined values like in the example, they are ObjectIds of other documents.
我已经研究了Distinct(),但似乎它只返回实际的唯一值,而不是文档本身.
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.
您可以通过uniqueVal进行$ group http://docs.mongodb.org/manual/reference/运算符/聚合/组/#pipe._S_group
You can $group by uniqueVal http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group
并使用$ first作为其他值 http://docs.mongodb.org/manual/reference/运算符/聚合/第一/#grp._S_第一
And use $first for the other values http://docs.mongodb.org/manual/reference/operator/aggregation/first/#grp._S_first
这篇关于如何在MongoDB中查找具有唯一值的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!