Meteor JS : How to use aggregate function ?

To use this mongoDB functionality you need to call directly your mongoDB. 

So , use this to connect in the mongoDB : 

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

Example :

In this example I’m using the aggregate role to calculate the distance of places stored in the database returning the 5 closest.

var longitude = "informed longitude"; 
var latitude = "informed latitude";

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var pipeline =[
    {
        $geoNear: {
            near: { type: "Point", coordinates: [longitude,latitude ]},
            distanceField: "dist.calculated",
            num: 5,
            includeLocs: "dist.location",
            spherical: true,
            sort: { distanceField :1 }
        }
    }
];


db.collection("place").aggregate(
    pipeline,
    Meteor.bindEnvironment(
        function(err, result){
            totalItems = result.length;
            // here you have the result
            console.log("totalItems" + totalItems);
        }
    )
);

Each place stored in the database has his latitude and longitude . In this example, the coordinates must be stored as follows to work properly:

loc: {
    type: "Point",
    coordinates: [longitude, latitude]
}

You need to store in this way to use aggregate function to do this and is required  to apply a geoNear index in your database.

db.collection.createIndex( { <location field> : “2dsphere” } )

To see more ( geoNear documentation ) :

http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/

2 Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s