@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public String[] queryAggregationCommand(Point point) {
String collectionName = mongoTemplate.getCollectionName(LocationInfo.class);
Query basicQuery = new BasicQuery("{actor : 1}");
NearQuery nearQuery = NearQuery
.near(point)/*以point为坐标点*/
.inKilometers()/*单位公里*/
.query(basicQuery)/*查询条件*/
.num(Integer.MAX_VALUE)/*返回记录数*/
.spherical(true)/*球面*/
.maxDistance(500);/*最大距离*/
Assert.notNull(nearQuery, "NearQuery must not be null!");
Assert.hasText(collectionName, "Entity class must not be null!");
DBObject geoNearFields = nearQuery.toDBObject();
geoNearFields.put("distanceField", "results.dis");
DBObject geoNear = new BasicDBObject("$geoNear", geoNearFields);
DBObject projectFields = new BasicDBObject();
projectFields.put("_id", 0);
projectFields.put("pushChannelId", 1);
String cmpJson = "{$cmp : ['$distance', '$results.dis']}";
DBObject cmpFields = (DBObject) JSON.parse(cmpJson);
projectFields.put("cmp", cmpFields);
DBObject project = new BasicDBObject("$project", projectFields);
String matchJson = "{$match : {cmp : {$gte : 0}}}";
DBObject match = (DBObject) JSON.parse(matchJson);
DBObject limit = new BasicDBObject("$limit", 10000);
/*
* Note:
* 1.使用$goNear只能在管道处理的开始第一个阶段进行
* 2.必须指定distanceField,该字段用来决定是否包含距离字段
* 3.$gonNear和geoNear命令比较相似,但是也有一些不同:distanceField在$geoNear中是必选的,
* 而在geoNear中是可选的;includeLocs在$geoNear中是string类型,而在geoNear中是boolen类型
* */
List<DBObject> pipeLine = Lists.newArrayList();
pipeLine.add(geoNear);
pipeLine.add(project);
pipeLine.add(match);
pipeLine.add(limit);
/*logger.debug("queryAggregationCommand:{}", pipeLine.toString());*/
AggregationOutput output = mongoTemplate.getCollection(collectionName).aggregate(pipeLine);
List<DBObject> list = (List<DBObject>) output.getCommandResult().get("result");
/*字段筛选*/
List<String> channels = Lists.transform(list, new Function<DBObject, String>() {
@Override
public String apply(DBObject input) {
return (String)input.get("pushChannelId");
}
});
String[] result = new String[channels.size()];
result = channels.toArray(result);
return result;
}
转载于:https://my.oschina.net/linwenbin/blog/419996