按near查询,排序,然后分页
我使用 MongoDB 中的地理空间“附近”搜索(使用 C# 驱动程序)来返回给定纬度/经度 25 英里以内的家。这会返回按纬度/经度的接近程度排序的房屋,并且效果很好。
但是,我想添加排序(在其他字段,例如房价)和分页,这就是我陷入困境的地方。为了正确工作,它需要找出哪些房屋位于纬度/经度 25 英里范围内,然后对这些结果进行排序(假设根据价格),然后获取包含 10 个结果的“页面”。
下面是我到目前为止所得到的,问题是它需要一页结果(基于邻近排序),然后根据我在“SetSortOrder”中设置的内容对该页 10 个结果进行排序,而不是对靠近排序的整个结果进行排序纬度/经度,因此每页 10 个结果都会自行排序。
var coordinates = find.GetCoordinates();
var near = Query.Near("Coordinates", coordinates.Latitude,
coordinates.Longitude,
find.GetRadiansAway(), false);
var query = Collection().Find(near);
query.Skip = find.GetSkip();
query.Limit = find.GetLimit();
query.SetSortOrder(new string[] { "Price" });
var results = query.ToArray();
I'm using the geospatial "near" search in MongoDB (using the C# driver) to return homes within 25 miles of a given lat/long. This returns the homes sorted by proximity to the lat/long and works great.
However, I want to add in sorting (on other fields such as home price) and paging and here is where I'm getting stuck. To work correctly, it would need to figure out which homes were within 25 miles of the lat/long, then sort those results (let's say based on price), and then take a "page" of 10 results.
Below is what I have so far, the issue with it is it takes a page of results (based on the proximity sort) and then sorts that page of 10 results by what I set in "SetSortOrder" rather than sorting the entire result near the lat/long, so each page of 10 results is sorted in itself.
var coordinates = find.GetCoordinates();
var near = Query.Near("Coordinates", coordinates.Latitude,
coordinates.Longitude,
find.GetRadiansAway(), false);
var query = Collection().Find(near);
query.Skip = find.GetSkip();
query.Limit = find.GetLimit();
query.SetSortOrder(new string[] { "Price" });
var results = query.ToArray();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的行为,因为 $near 默认返回按距离排序的结果。并且排序在 $near 运算符内部完成,因此您无法更改它。
因此在您的示例中
Price
它是第二个排序字段,用于对按距离排序的结果中的数据进行排序。Workgraund 加载 Query.Near 的整个结果,然后根据客户端上您想要的字段对其进行排序。
It is right behavior, because $near by default return result sorted by distance. And sorting done internally in $near operator, so you can't change it.
So in you example
Price
it's second sort field that sort data within result sorted by distance.Workgraund is load entire result of
Query.Near
and than sort it by whatever you want field on the client.