虽然这适用于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]
我确实看到需要直接使用集合的操作来完成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
。
我甚至无法编译@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;