MongoDB聚合,使用项目计算字段,并使用此字段排序

MongoDB聚合,使用项目计算字段,并使用此字段排序,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我想使用MongoDB聚合框架来实现这一点,这可能吗 db.objects.aggregate([ {$match: {$and:[ {location:{$nearSphere:{$geometry:{type:"Point",coordinates:[latitude, longitude]},$minDistance:x,$maxDistance:y}}}, {date1:{$gte:date2}

我想使用MongoDB聚合框架来实现这一点,这可能吗

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

使用db.collection.group({key,reduce,initial[,keyf][,cond][,finalize]})可以这样做吗?…

是的,您应该可以这样做。无论如何,您不需要在第一个
$match
上使用
$和
运算符,默认情况下这两个条件在
$和
中。只需编写
$match:{location:{…},date1:{…}
。另外,在
$project
中,您必须将
ratio
定义为一个对象键:
$project:{ratio:{$divide…}}
。以及如何调用函数返回距离?…您可以定义用于查询的javascript函数,看看这个答案()。对于计算两个lat-long坐标之间距离的算法,您可以检查这个()我们可以看看是否可以使用聚合框架执行您的函数正在执行的操作吗?我看到您不能使用聚合框架调用javascript函数,这是不可能的。但是你可以用地图缩小。。。