符合条件的MongoDB Spring,距文档字段的最大距离

时间:2018-07-30 12:13:19

标签: java mongodb spring-data spring-data-mongodb

我正在尝试使用在文档字段中定义的最大距离来制定一个insphere准则,但是我对此一无所获。我刚刚发现了如何用数字设置最大距离,而没有用字段名称设置。

我的文档中有这些字段:

  • id:字符串
  • basePosition:GeoJsonPoint
  • nearEnabled:布尔值
  • nearMaxDistance:整数

我使用MongoTemplate进行查询:这是我的查询代码

public GeoResults<MyEntity> searchQuery(double latitude, double longitude, Integer maxDistanceKm, Long skip, Integer limit) {
GeoJsonPoint point = new GeoJsonPoint(longitude, latitude);

// Simple fields criteria
Query mongoQuery = new Query().addCriteria(
        // I have one simple where here but i removed it for the post
);

mongoQuery.addCriteria(
    new Criteria().orOperator(
        new Criteria().andOperator(
            Criteria.where("nearEnabled").is(true)
            //TODO need to add my withinSphere here, with field basePosition as center point and field nearMaxDistance as limit radius
        )
        // I have another and operator with 2 where here but i removed it for the post
    )
);

long skipPrimitive = skip != null ? skip : 0;
NearQuery nearQuery = NearQuery.near(point).query(mongoQuery).skip(skipPrimitive).spherical(true);

if(maxDistanceKm != null) nearQuery = nearQuery.maxDistance(maxDistanceKm, Metrics.KILOMETERS);
if(limit != null) nearQuery.num(skipPrimitive + limit);

GeospatialIndex geoIndex = new GeospatialIndex("basePosition").typed(GeoSpatialIndexType.GEO_2DSPHERE);
mongoTemplate.indexOps(ProfileEntity.class).ensureIndex(geoIndex);

return mongoTemplate.geoNear(nearQuery, MyEntity.class);}

正如我们在代码中看到的那样,我还有其他一些条件,分页和我基于Sphere的字段必须在or>和运算符中。 我在nearQuery上也有一个全局maxDistance。

我在查询中搜索了一种方法来执行此操作。 否则,我可以在服务上应用Java列表过滤器,但是它将在分页之后运行,并且将打破每页结果数的概念,而直接在查询中执行此操作将避免此问题。

0 个答案:

没有答案