0

好的,我要做的是找到在聚合管道中添加 $geoNear 的正确方法。我已经通过在聚合管道列表中添加一个 org.bson.Document 来做到这一点,但我认为应该有一种更清晰的方法来使用最新的官方 mongoDB Java-Driver 来实现它。例如,为了对 $group、$project、$match 执行此操作,mongoDB Java-Driver 提供了 Aggregates 类,相关调用是:

Aggregates.group, Aggregates.project, Aggregates.match. 我正在寻找的是类似的东西:Aggregates.geoNear,这是缺席的。我的示例代码如下所示:

createDocumentCollection()
            .aggregate(
                Arrays.asList(
                    // geoNear spherical geometry for 2d sphere
                    new Document("$geoNear", new Document()
                        .append("near", new Document()
                            .append("$geometry", new Document()
                                .append("type", "Point")
                                .append("coordinates", Arrays.asList(longitude, latitude)))
                            .append("$maxDistance", maxDistance))
                        .append("key", "avgGeoPoint")
                        .append("distanceField", "dist.calculated")),
                    // group
                    Aggregates.group("$mmsi",
                        Accumulators.first("mmsi", "$mmsi"),
                        Accumulators.first("vesselName", "$vesselName"),
                        Accumulators.first("shipType", "$shipType")),
                    // projection
                    Aggregates.project(Projections.fields(
                        Projections.excludeId(),
                        Projections.include("mmsi", "vesselName", "shipType"))),
                    // skip
                    Aggregates.skip(options.getSkip()),
                    // limit
                    Aggregates.limit(options.getLimit())))
            .map(ModelExtractor::extractPlainVessel)
            .forEach((Consumer<PlainVessel>) nearVessels::add);

我要替换的部分是这样的:

new Document("$geoNear", new Document()
           .append("near", new Document()
               .append("$geometry", new Document()
                   .append("type", "Point")
                   .append("coordinates", Arrays.asList(longitude, latitude)))
               .append("$maxDistance", maxDistance))
            .append("key", "avgGeoPoint")
            .append("distanceField", "dist.calculated"))
4

0 回答 0