【问题标题】:meteor query for all documents with unique field流星查询具有唯一字段的所有文档
【发布时间】:2015-09-09 07:21:38
【问题描述】:

我想完全按照SO question 的目的做,但在服务器端使用 Meteor:

如何检索具有唯一值的所有文档 领域?

> 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,我也很乐意以其他方式获取具有唯一字段的文档。

【问题讨论】:

  • 它不能直接作为捆绑提供,但您可以安装陨石来启用它。您也可以通过访问底层驱动程序来获得它。它只在“服务器”上可用,因为在“客户端”上它无论如何都没有任何意义,因此为什么不是标准包含。周围有很多例子。我自己写了一些。
  • @BlakesSeven - 你能指出我如何访问底层驱动程序来解决我的问题的例子吗?我已经搜索过,但没有找到。

标签: mongodb meteor mongodb-query aggregation-framework


【解决方案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 中有一个类似流程的完整工作示例应用程序,以及this question 上的meteor hacks aggregate 包的用法,如果您需要进一步参考。

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2011-09-02
    • 2014-12-19
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多