具有唯一字段的所有文档的流星查询

时间:2015-09-09 07:21:39

标签: mongodb meteor mongodb-query aggregation-framework

我想完全按照SO question获得的内容,但在服务器端使用Meteor:

  

如何检索具有唯一a值的所有文档   场?

> db.foo.insert([{age: 21, name: 'bob'}, {age: 21, name: 'sally'}, {age: 30, name: 'Jim'}])
> db.foo.count()
3
> db.foo.aggregate({ $group: { _id: '$age', name: { $max: '$name' } } }).result
[
    {
        "_id" : 30,
        "name" : "Jim"
    },
    {
        "_id" : 21,
        "name" : "sally"
    }
]

我的理解是,aggregate不适用于Meteor。如果这是正确的,我怎样才能实现上述目标?事后对查询执行后置过滤不是理想的解决方案,因为我想使用limit。只要我可以使用limit,我也很乐意以其他方式获取具有唯一字段的文档。

1 个答案:

答案 0 :(得分:1)

您可以使用常规设置来访问底层驱动程序集合对象,因此.aggregate()无需安装任何其他插件。

基本过程如下:

FooAges = new Meteor.Collection("fooAges");

Meteor.publish("fooAgeQuery", function(args) {
    var sub = this;

    var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    var pipeline = [
        { "$group": {
            "_id": "$age", 
            "name": { "$max": "$name" }
        }}
    ];

    db.collection("foo").aggregate(        
        pipeline,
        // Need to wrap the callback so it gets called in a Fiber.
        Meteor.bindEnvironment(
            function(err, result) {
                // Add each of the results to the subscription.
                _.each(result, function(e) {
                    // Generate a random disposable id for aggregated documents
                    sub.added("fooAges", Random.id(), {
                        "age": e._id,
                        "name": e.name
                    });
                });
                sub.ready();
            },
            function(error) {
                Meteor._debug( "Error doing aggregation: " + error);
            }
        )
    );

});

因此,您为聚合的输出定义了一个集合,并在这样的例程中,然后发布您将在客户端中订阅的服务。

在此内部,聚合运行并填充到另一个集合中(逻辑上它实际上并没有写任何东西)。然后,您在客户端上使用具有相同定义的集合,并且只返回所有聚合结果。

如果您需要进一步参考,我实际上在this question内有一个类似流程的完整工作示例应用,以及meteor hacks aggregatethis question包的使用情况。

相关问题