MongoDB $ geonear和$ group by object属性

时间:2018-03-05 11:26:41

标签: node.js mongodb mongoose

我有很多文件的这个集合:

{
 "type"      : "Feature",
 "geometry"  : {
  "type"        : "Point",
  "coordinates": [
    19.038526,
    39.409768
  ]
},
 "properties": {
  "title"    : "xxx",
  "address"  : "xxx",
  "areaMajor": "Area 1",
  "areaSub1" : "xxx",
  "areaSub2" : "xxx",
  "email"    : "xxx",
  "tel1"     : "xxx",
  "tel2"     : "xxx",
  "fax"      : "xxx",
  "hours"    : "xxx",
  "site"     : "xxx",
  "facebook" : "xxx"
 }
},
{
 "type"      : "Feature",
 "geometry"  : {
  "type"        : "Point",
  "coordinates": [
    18.038526,
    35.409768
  ]
},
 "properties": {
  "title"    : "xxx",
  "address"  : "xxx",
  "areaMajor": "Area 2",
  "areaSub1" : "xxx",
  "areaSub2" : "xxx",
  "email"    : "xxx",
  "tel1"     : "xxx",
  "tel2"     : "xxx",
  "fax"      : "xxx",
  "hours"    : "xxx",
  "site"     : "xxx",
  "facebook" : "xxx"
 }
}
...

然后我使用此聚合来查找附近的地点,然后按properties.areaMajor对其进行分组,并计算此areaMajor内的位置数。

 Area.aggregate(
        ([
            { "$geoNear": {
                    "near": {type: 'Point', coordinates:[24.038526,38.409768]} ,
                    "spherical": true,
                    "distanceField": "distance",
                    "distanceMultiplier": 6371
                }},
            {'$group': {
               _id: {
                     areaMajor: '$properties.areaMajor', 
                     areaSub1: '$properties.areaSub1', 
                     distance: '$distance'
                },
               count: {$sum: 1}}
            },
            { "$sort": { "distance": -1} },
         ])
    ).exec((err, area) => {
        if (err) {
            console.log(err)
            return res.status(500).json({
                title: 'error',
                error: {message: 'error message'}
            });
        }
            if (!area) {
                return res.status(404).json({
                    title: 'error',
                    error: {message: 'error message'}
                });
            }
        res.status(200).json(area);
    });

输出会返回许多重复项,我该如何正确分组?

当前输出:

{
    "_id": {
        "areaMajor": "Area 1",
        "areaSub1": "xxxx",
        "distance": 1805205937.2356606
    },
    "count": 1
},
{
    "_id": {
        "areaMajor": "Area 1",
        "areaSub1": "xxxx",
        "distance": 1804386562.3484473
    },
    "count": 1
},
{
    "_id": {
        "areaMajor": "Area 2",
        "areaSub1": "xxxx",
        "distance": 104486562.3455322
    },
    "count": 1
},
{
    "_id": {
        "areaMajor": "Area 2",
        "areaSub1": "xxxx",
        "distance": 203486562.3556778
    },
    "count": 1
}

预期产出:

 {
    "_id": {
        "areaMajor": "Area 1",
        "distance": 313110.6166765188
    },
    "count": 50
},
{
    "_id": {
        "areaMajor": "Area 2",
        "distance": 304502.5085277966
    },
    "count": 20
}

0 个答案:

没有答案