使用Aggregate模拟.distinct(),但在MongoDB中使用find语句

使用Aggregate模拟.distinct(),但在MongoDB中使用find语句,mongodb,set,aggregation-framework,Mongodb,Set,Aggregation Framework,我知道.distinct()和聚合管道是不同的,不能相互操作。但是,我想使用聚合管道生成一个返回集,如.distinct()命令,但首先要使用find({query})来过滤记录 因此,如果使用distinct,我可以: > db.coll.distinct('institution.name') [ "MySite", "MySite2", "Stack Overflow", "Google", ..etc. ] 对于我想做的聚合,使用params上的子集,其中{“users”:{$g

我知道.distinct()和聚合管道是不同的,不能相互操作。但是,我想使用聚合管道生成一个返回集,如.distinct()命令,但首先要使用find({query})来过滤记录

因此,如果使用distinct,我可以:

> db.coll.distinct('institution.name')
[
"MySite",
"MySite2",
"Stack Overflow",
"Google",
..etc.
]
对于我想做的聚合,使用params上的子集,其中{“users”:{$gt:1000000}。因此,我想要一个类似的数组输出,查找所有不同的名称:

> db.coll.aggregate([ 
    {$group:{_id:{"users": {$gt: 1000000}}, array:{"institution.name"????}}}, 
]);
[
"Stack Overflow",
"Google",
..etc.
]

如果看不到您的收藏结构,很难准确地说出来,但您似乎可以通过以下方式获得您想要的答案:


您可以将查询传递给distinct。使用以下语法:

> db.coll.distinct('institution.name',  {"users": {$gt: 1000000}} )
聚合框架的正确语法为:

db.coll.aggregate([
    {$match:{"$users": {$gt: 1000000}},
    {$group:{
        _id:null, 
        array:{"$addToSet":"$institution.name"}
    }}, 
]);
你看过$addToSet吗?
db.coll.aggregate([
    {$match:{"$users": {$gt: 1000000}},
    {$group:{
        _id:null, 
        array:{"$addToSet":"$institution.name"}
    }}, 
]);