查询mongodb以搜索集合中lats和lng的计数

时间:2017-05-15 13:46:40

标签: mongodb

我的文件包含以下详细信息..

{ 
        "_id" : ObjectId("58fa2847a105621bf28c7436"), 
        "srcLoc" : [ 29.03596937656403, 41.08048413380768 ], 
        "destLoc" : [ 29.3168603, 40.905371 ], 
        "wayPoints" : [ 
            { "_id" : ObjectId("58fa2961de50171c2e89e4e2"),
             "lng" : 29.035865853970662,
              "lat" : 41.08010057266194 
            },
            { "_id" : ObjectId("58fa2961de50171c2e89e4e1"), 
             "lng" : 29.053879848358697, 
             "lat" : 41.082083123947546 
            },
            { "_id" : ObjectId("58fa2961de50171c2e89e4e0"), 
             "lng" : 29.0638848389565, 
             "lat" : 41.0857235683904 
            },
            { "_id" : ObjectId("58fa2961de50171c2e89e4df"), 
             "lng" : 29.03194416492813, 
             "lat" : 41.0566495985393 
            } 
        ],
        "totalDistance" : 0.004627394567308733,
        "driverId" : ObjectId("58ecd6a563b5128b2b5e298b"),
        "riderId" : ObjectId("58ececcbb5e88b94e59e0cd1"),
        "__v" : 0 
        }

此处字段“wayPoints”具有中间点lats-lngs对。而且我必须找到哪个lat-lng对在大多数情况下都会出现在集合中的场所...对于例如。我假设来自wayPoints字段的lat-lng对     [“lng”:29.035865853970662,       “lat”:41.08010057266194] 我需要以所有方式计算此lat-lng对的出现次数属于该集合。

1 个答案:

答案 0 :(得分:0)

尝试此聚合框架查询:

db.stackoverflow.aggregate(
[
    {$unwind: "$wayPoints"},
    {$group: 
        {
        _id: {lng:"$wayPoints.lng", lat:"$wayPoints.lat"},
        count: {$sum:1}
        }
    },
    {$sort: {count:-1}}
]
)

我创建了一些类似你提供的文档然后我在集合上运行了这个查询,结果如下。您可以看到,对于每个lat-lng对,都有一个出现的计数器,它们从最常用的对开始排序(3次出现)。

{ 
    "_id" : {
        "lng" : 29.035865853970662, 
        "lat" : 41.08010057266194
    }, 
    "count" : NumberInt(3)
}
{ 
    "_id" : {
        "lng" : 29.0638848389565, 
        "lat" : 41.0857235683904
    }, 
    "count" : NumberInt(2)
}
{ 
    "_id" : {
        "lng" : 29.053879848358697, 
        "lat" : 41.08208312394755
    }, 
    "count" : NumberInt(2)
}
{ 
    "_id" : {
        "lng" : 29.03194416492813, 
        "lat" : 41.0566495985393
    }, 
    "count" : NumberInt(2)
}
{ 
    "_id" : {
        "lng" : 49.0638848389565, 
        "lat" : 61.0857235683904
    }, 
    "count" : NumberInt(1)
}
{ 
    "_id" : {
        "lng" : 39.0538798483587, 
        "lat" : 51.08208312394755
    }, 
    "count" : NumberInt(1)
}
{ 
    "_id" : {
        "lng" : 59.03194416492813, 
        "lat" : 71.0566495985393
    }, 
    "count" : NumberInt(1)
}