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] }) ?...

5
  • 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 ... } }. Commented Jul 11, 2018 at 15:24
  • And how to call the function returning distance ?... Commented Jul 11, 2018 at 15:47
  • You can define javascript functions to use in queries, take a look at this answer (stackoverflow.com/a/31497321/10026557). For an algorithm to calculate distance between two lat long coordinates you can check this one (stackoverflow.com/a/27943/10026557) Commented Jul 11, 2018 at 15:59
  • Can we see whether it's possible to do what you function is doing with the Aggregation Framework? Commented Jul 11, 2018 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... Commented Jul 11, 2018 at 16:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.