meteor query for all documents with unique field

后端 未结 1 1432
鱼传尺愫
鱼传尺愫 2021-01-26 10:47

I want to do exactly what this SO question gets at but with Meteor on the server side:

How do I retrieve all of the documents which HAVE a unique value of

相关标签:
1条回答
  • 2021-01-26 11:03

    There is a general setup you can use to access the underlying driver collection object and therefore .aggregate() without installing any other plugins.

    The basic process goes like this:

    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);
                }
            )
        );
    
    });
    

    So you define a collection for the output of the aggregation and within a routine like this you then publish the service that you are also going to subscribe to in your client.

    Inside this, the aggregation is run and populated into the the other collection ( logically as it doesn't actually write anything ). So you then use that collection on the client with the same definition and all the aggregated results are just returned.

    I actually have a full working example application of a similar processs within this question, as well as usage of the meteor hacks aggregate package on this question here as well, if you need further reference.

    0 讨论(0)
提交回复
热议问题