MongoDB $geoNear 在聚合管道中使用最新的 Java 驱动程序

时间:2021-01-07 23:49:49

标签: java mongodb mongodb-query aggregation-framework mongodb-java

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

Aggregates.groupAggregates.projectAggregates.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"))

0 个答案:

没有答案