0

I would like to do this using MongoDB aggregation-framework, is this possible?

db.objects.aggregate([
    {$match:
        {$and:[
              {location:{$nearSphere:{$geometry:{type:"Point",coordinates:[latitude, longitude]},$minDistance:x,$maxDistance:y}}},

              {date1:{$gte:date2}
              ]
        }
    },
    {$project:ratio
        {$divide:[
                 {$subtract:[date1,date2]},

                 {result of a function returning distance between this location and latitude, longitude in parameters}
                 ]
        }
    },
    {$sort:{ratio:-1}}
]);

Is this possible to do this with db.collection.group({ key, reduce, initial [, keyf] [, cond] [, finalize] }) ?...

L.G
  • 1,458
  • 4
  • 14
  • 24
  • Yes you should be able to do that. Anyway you don't need to use the `$and` operator on the first `$match`, the two conditions are in `$and` by default. Just write `$match: { location: { ... }, date1: { ... } }`. Also in your `$project` you must define `ratio` as an object key: `$project: { ratio: {$divide ... } }`. – cornacchia Jul 11 '18 at 15:24
  • And how to call the function returning distance ?... – L.G Jul 11 '18 at 15:47
  • You can define javascript functions to use in queries, take a look at this answer (https://stackoverflow.com/a/31497321/10026557). For an algorithm to calculate distance between two lat long coordinates you can check this one (https://stackoverflow.com/a/27943/10026557) – cornacchia Jul 11 '18 at 15:59
  • Can we see whether it's possible to do what you function is doing with the Aggregation Framework? – styvane Jul 11 '18 at 16:20
  • I see you can’t call a javascript function with the aggregation framework, it’s not possible. But you can with map reduce... – L.G Jul 11 '18 at 16:45

0 Answers0