Javascript Mongodb geoNear和组聚合

Javascript Mongodb geoNear和组聚合,javascript,mongodb,mongoose,aggregation-framework,Javascript,Mongodb,Mongoose,Aggregation Framework,我一直在网上搜索与此相关的东西,但无法找到 我有这种愤慨 Place.aggregate( [ { "$geoNear": { "near": { "type": "Point", "coordinates": [longitude, latitude] }, "spherical": true, "distan

我一直在网上搜索与此相关的东西,但无法找到

我有这种愤慨

 Place.aggregate(
    [
        { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [longitude, latitude]
            },
            "spherical": true,
            "distanceField": "distance"
        }},
        { $group:
        {   _id: "$_id",
            name: { '$first': '$name' },
            distance: { $first: "$distance" }
        }
        },
        { $project : {
            name: 1,
            distance: 1,
        }}
    ],
    function(error, places) {
        if (error) return callback(error, null);
        callback(null, places)
    }
);
它可以工作,但是geoNear排序丢失了

但这给了我正确排序的文档:

    Place.aggregate(
    [
        { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [longitude, latitude]
            },
            "spherical": true,
            "distanceField": "distance"
        }}
    ],
    function(error, places) {
        if (error) return callback(error, null);
        callback(null, places)
    }
);
有什么想法吗

为了让你了解我在这里试图做什么,我使用了完整的查询

    Place.aggregate(
    [
        { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [longitude, latitude]
            },
            "spherical": true,
            "distanceField": "distance"
        }},
        {"$unwind": "$participants" } ,
        { $group:
        {   _id: "$_id",
            name: { '$first': '$name' },
            distance: { $first: "$distance" },
            person: { $sum: 1 },
            sumof:{ $sum: "$participants.age"}
        }
        },
        { $project : {
            name: name,
            distance: 1,
            person: 1,
            meanAge:{ $divide: [ "$sumof", "$person" ]}
        }}
    ],
    function(error, places) {
        if (error) return callback(error, null);
        callback(null, places)
    }
);

简而言之,当您使用运算符等时,无法保证返回结果的顺序。文档将按照“输入”到组管道的顺序进行处理,以尊重诸如
$first
之类的内容,但输出的顺序不一定与输入的顺序相同

直接从文档中获取:

$group不为其输出文档排序

事实上,您可能会发现顺序是按分组键排列的,但在大多数情况下是相反的

如果您想要有一个特定的输出顺序,那么在最终的“输出”中使用and,这应该是您的最后一个管道阶段,所以其他任何东西都不会改变该顺序

Place.aggregate(
[
{“$geoNear”:{
“近”:{
“类型”:“点”,
“坐标”:[经度、纬度]
},
“球形”:正确,
“距离字段”:“距离”
}},
{“$unwind”:“$participants”},
{“$group”:{
“\u id”:“$\u id”,
“名称”:{“$first”:“$name”},
“距离”:{“$first”:“$distance”},
“人”:{“$sum”:1},
“sumof”:{“$sum”:“$participants.age”}
}},
{“$project”:{
“名称”:1,
“距离”:1,
“人”:1,
“平均年龄”:{“$divide”:[“$sumof”,“$person”]}
}},
{“$sort”:{“距离”:1}
],
回拨
);

您在主键“\u id”上分组,而主键实际上不起任何作用。你为什么要那样做?你还想在这里做些什么吗?我展示的代码被简化了,我的目标是通过geoNear对带有自定义字段(使用组和项目)的文档进行排序。我编辑了我的问题,我希望我现在要做的应该更清楚。