问题描述
我们有以下数据:
[
{
"location" : {
"type" : "POINT","coordinates" : [
-92.41151,35.11683
]
},"geoHash" : "dr72jwgnbbst"
},{
"location" : {
"type" : "POINT","coordinates" : [
-89.58342,36.859161
]
},"geoHash" : "dn6qtkr5xk8m"
},"coordinates" : [
-86.038762,36.519016
]
},"geoHash" : "dn6zf0h6xtcp"
},"coordinates" : [
-98.3081936,26.2143207
]
},"geoHash" : "9udj4unjmp9f"
},"coordinates" : [
-98.5377275,29.4878928
]
},"geoHash" : "9v1zv8p52t8u"
},"coordinates" : [
-73.7018126,42.641387
]
},"geoHash" : "dreddfeup69m"
},"coordinates" : [
-111.865295,33.431942
]
},"geoHash" : "9tbqnqn5jtwq"
},"coordinates" : [
-79.810763,34.174603
]
},"geoHash" : "dnp4rv796rtz"
}]
我们需要查询以获取以“dn”、“9t”、“dr”、“9v”、“9u”开头的 geohashes 的位置,并且每个 geo hash 只应返回一个位置。例如,我们有 3 个位置的 geohash 以“dn”开头,但它应该只返回任何一个位置。 输出:
"dr" -> "location" : {
"type" : "POINT","coordinates" : [
-92.41151,35.11683
]
}
"dn" -> "location" : {
"type" : "POINT","coordinates" : [
-89.58342,36.859161
]
}
"9u" -> "location" : {
"type" : "POINT","coordinates" : [
-98.3081936,26.2143207
]
}
"9v" -> "location" : {
"type" : "POINT","coordinates" : [
-98.5377275,29.4878928
]
}
"9t" -> "location" : {
"type" : "POINT","coordinates" : [
-111.865295,33.431942
]
}
谢谢
解决方法
如果您总是检查 geoHash
的前两个字符,请尝试 bebow 查询:
db.locations.aggregate([
{
$match: {
geoHash: {
$regex: '^dn|^9t|^dr|^9v|^9u',$options: 'i'
}
}
},{
$addFields: {
geoHashSubStr: {
$substr: ["$geoHash",2]
}
}
},{
$group: {
_id: "$geoHashSubStr",// Group other fields based on your requirement.
location: {
$first: "$location"
}
}
}
])
,
给你。
- 按
geoHash
的前 2 个字符对所有结果进行分组。 - 仅投影该数组的第一个元素。
db.collection.aggregate([
{
$group: {
_id: {
$substr: [
"$geoHash",2
]
},locations: {
$push: "$location"
}
}
},{
"$project": {
_id: true,location: {
$arrayElemAt: [
"$locations",0
]
}
}
}
])