spring-data-mongodb中geoNear中的distanceField

时间:2014-07-02 06:16:37

标签: mongodb spring-data-mongodb

我使用的是spring-data-mongodb。

  1. 我可以使用聚合激活geoNear查询。
  2. 我可以像在mongodb中一样在geoNear查询中指定distanceField。
  3. 以下是mongodb查询示例: -

    ([
    {
        $geoNear: {
            near: [
                28.45,
                77.34
            ],
            distanceField: "distance",
            maxDistance: 20,
            num: 5,
            query: {
                $or: [
                    {
                        cuisines: {
                            '$in': [
                                'Mughlai',
                                'NorthIndian'
                            ]
                        }
                    }
                ]
            }
        }
    },
    {
    $unwind: '$ProducerTimeSlots'
    }
    ])
    

1 个答案:

答案 0 :(得分:0)

您需要扩展聚合操作功能,GeoNearOperations类没有distanceField变量。

public class GeoNearOperationExt implements AggregationOperation {

private NearQuery nearQuery;

private String distanceField = "distance";

public GeoNearOperationExt(NearQuery nearQuery) {
    this.nearQuery = nearQuery;
}

/**
 * Default is distance
 * @return
 */
public String getDistanceField() {
    return distanceField;
}

/**
 * Set distanceField value Default is distance
 * @param distanceField
 */
public void setDistanceField(String distanceField) {
    this.distanceField = distanceField;
}



@Override
public DBObject toDBObject(AggregationOperationContext context) {
    DBObject dbObject = context.getMappedObject(nearQuery.toDBObject());
    dbObject.put("distanceField", distanceField);
    return new BasicDBObject("$geoNear", dbObject);
}
}

要在聚合中使用它,只需将其包含在聚合操作数组中,即传递给聚合函数的参数。