gpt4 book ai didi

python - 如何按 mongodb 中 $geonear 聚合管道中的其他字段排序

转载 作者:行者123 更新时间:2023-12-01 05:09:52 26 4
gpt4 key购买 nike

我的收藏就是这种格式。

{
"_id" : ObjectId("52e5f94d83b45407f959e7ff"),

"latlng" : {
"coordinates" : [
85.29035240000007,
27.6663671
],
"type" : "Point"
},
"name" : "Sujit Maharjan",
"updates" : [
{
"status" : "I want to #buy 5 kg of tomatoes.",
"picture" : [ ],
"parent_tweet_id" : "0",
"deleted" : 1,
"tweet_id" : "428578269169205248",
"time_stamp" : 1391015996
}
{
"status" : "I want to #start #milk business who can help me ?",
"picture" : [ ],
"parent_tweet_id" : "0",
"deleted" : 0,
"tweet_id" : "108fd43a-7efa-404d-800d-0c30a5da06e5",
"time_stamp" : 1391955084
},
{
"status" : "@SantoshGhimire @bhanduroshan Connect to us for #Dairy business",
"picture" : [ ],
"parent_tweet_id" : "432503201968168960",
"deleted" : 1,
"tweet_id" : "432517594026082304",
"time_stamp" : 1391955208
},
{
"status" : "@bhanduroshan Did you get my message ?",
"picture" : [ ],
"parent_tweet_id" : "432502654154334208",
"deleted" : 0,
"tweet_id" : "432788670463377408",
"time_stamp" : 1392019838
},
{
"status" : "this is tweet with images @foodtradeHQ http://t.co/3eL1351HWf",
"picture" : [
"http://pbs.twimg.com/media/BgLZ4YaCUAAsFTJ.jpg"
],
"parent_tweet_id" : "0",
"deleted" : 1,
"tweet_id" : "433148076820156417",
"time_stamp" : 1392105574
}
]
}

现在我需要查询用户在一定半径内按up​​dates.time_stamp排序的更新。

为此,我使用了聚合管道,但 $geonear 查询会根据距离进行排序并限制结果。

这是我在 python 中的管道

    geo_search = {"near": [float(self.lng), float(self.lat)],
"distanceField": "distance",
"includeLocs": "latlng",
"uniqueDocs": True,
"spherical":True,
"limit":100, # this will cut off the possible results, and complexity increasing in increasing this number
}



pipeline = []

final_query = {"$and":query_string}

if len(query_string)>0:
geo_search['query'] = final_query


geo_search['maxDistance'] = 0.01261617096

geo_near = {
"$geoNear": geo_search
}


pipeline.append(geo_near)

最佳答案

$geoNear聚合管道阶段,这基本上执行标准类型的“nearSphere”或“near”之类的查询,但将结果文档放入管道中,并带有 distanceField 所需的附加字段。

必须是第一个管道阶段,可以在其中使用索引:

 collection.aggregate([
{ "$geoNear": {
"near": [ float(self.lng), float(self.lat) ],
"maxDistance": 0.01261617096,
"distanceField": "distance",
"includeLocs": "latlng",
"uniqueDocs": True,
"spherical":True,
"query": {
"updates.time_stamp": {
"$gte": timestamp_cutoff
}
},
"limit":100
}},
{ "$sort": { "other": 1, "distance": 1 } }
])

通过管道的其余部分,现在存在“distanceField”中定义的附加字段,因此为了获得最接近的结果,请将其传递给 $sort 。您可以传递任何您想要排序的内容,因为这就是管道阶段的作用。

您基本上可以根据结果采取任何您喜欢的操作,包括其他阶段,例如 $match当然,如果其他信息与初始结果相关,那么您可以使用 $geoNear 的“查询”选项。 .

实际上,要做你想做的事情,你需要通过使用“查询”中的某些内容来“限制”可能匹配的文档,如图所示。因此,返回的“最近”文档只是那些符合附加条件的文档。

关于python - 如何按 mongodb 中 $geonear 聚合管道中的其他字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com