geoQuery的不同值在Mongo中有效,但在Spring中无效

问题描述 投票:1回答:2

虽然这适用于mongo:

> db.collection.distinct( "key", {"position":{$geoWithin:{$box: [[-6.8, 36.7], [-0.5, 43.8]]}}} )
> [ "A", "B" ]

在春天返回一个错误

Criteria criteria = Criteria.where("position").within(box);
        Query query = new Query();
        query.addCriteria(criteria);
 List<String> result = mongoOperations.getCollection("collection")
                .distinct("key", query.getQueryObject());

java.lang.IllegalArgumentException:无法在org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:299)〜[mongo-java-driver-2.14.3]中序列化org.springframework.data.mongodb.core.query.GeoCommand类。 .jar:na] at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:194)〜[mongo-java-driver-2.14.3.jar:na] at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:255 )org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:194)〜[mongo-java-driver-2.14.3.jar:na .bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:255)〜[mongo-java-driver-2.14.3.jar:na] at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:194)~ [mongo-java-驱动程序-2.14.3.jar:na] at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:136)〜[mongo-java-driver-2.14.3.jar:na] at com.mongodb.DefaultDBEncoder.writeObject(在DB.mongodb.OutMessage.putObject(OutMessage.java:289)的DefaultDBEncoder.java:36)〜[mongo-java-driver-2.14.3.jar:na] 〜[mongo-java-driver-2.14.3.jar:na] at com.mongodb.OutMessage.writeQuery(OutMessage.java:211)〜[mongo-java-driver-2.14.3.jar:na] at com。 mongodb.OutMessage.query(OutMessage.java:86)〜[mongo-java-driver-2.14.3.jar:na]

spring mongodb geolocation distinct
2个回答
0
投票

我确实看到需要直接使用集合的操作来完成MongoDB Java驱动程序API。然而Query.getQueryObject()不能直接与底层驱动程序一起使用,因为它被QueryMapper转换。现在,您可以尝试自己进行映射。

QueryMapper mapper = new QueryMapper(mongoOperations.getConverter());
org.bson.Document mappedQuery = mapper.getMappedObject(query.getQueryObject(), Optional.empty());

List<String> result = template.getCollection("collection")
    .distinct("key", mappedQuery, String.class)
    .into(new ArrayList<>());

还有DATAMONGO-1761(艰难仍然开放)寻求增加对distinct的支持MongoOperations


0
投票

我甚至无法编译@Christoph Strobl代码!

我终于使用mongo-java-driver来获取不同的值:

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase(dbName);
    MongoCollection<org.bson.Document> collection = database.getCollection(COLLECTION);
    Bson query = Filters.geoWithinBox("position", 
            x1, y1, x2, y2);

    DistinctIterable<String> resultList = collection.distinct("key", query, String.class);

    Set resultSet = new HashSet();
    resultList.forEach(new Block<String>() {
        @Override
        public void apply(final String result) {
            resultSet.add(result);
        }
    });

    return resultSet;
© www.soinside.com 2019 - 2024. All rights reserved.