'Why do I get the following error : Can't find a codec for class com.mongodb.client.model.geojson.Polygon
I am trying to do a geospatial query using MongoDB's com.mongodb.client.model.geojson.Polygon class and com.mongodb.client.model.geojson.Position class. The client code populates the four double corners in its own boundingBox object.
Here is the code snippet:
Polygon polygon = new Polygon(Arrays.asList(new Position(boundingBox.getRightLongitude(),boundingBox.getTopLatitude()),
new Position(boundingBox.getLeftLongitude(), boundingBox.getTopLatitude()),
new Position(boundingBox.getLeftLongitude(), boundingBox.getBottomLatitude()),
new Position(boundingBox.getRightLongitude(), boundingBox.getBottomLatitude()),
new Position(boundingBox.getRightLongitude(), boundingBox.getTopLatitude())));
//Document filter = new Document("coordinates",geoWithin("coordinates", polygon));
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
database.getCollection("roads").find(geoWithin("coordinates",polygon)).forEach(printBlock);
And here is the error:
Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.mongodb.client.model.geojson.Polygon.
Solution 1:[1]
In your settings you need to specify the codec registry, you're currently missing GeoJsonCodecProvider() using com.mongodb.MongoClient.getDefaultCodecRegistry() should do fine
For the async driver
MongoClientSettings settings = MongoClientSettings.builder().readPreference(readPreference)
.codecRegistry(com.mongodb.MongoClient.getDefaultCodecRegistry()).socketSettings(sockSettings)
.connectionPoolSettings(connPoolSettings).credentialList(credentials))
.clusterSettings(clusterSettings).build();
LOG.info("MongoClientSettings: {}, {}, {}, {}", sockSettings, connPoolSettings, clusterSettings, credentials);
MongoClient mgc = MongoClients.create(settings);
for the normal driver
MongoClientOptions settings = MongoClientOptions.builder().readPreference(readPreference)
.codecRegistry(com.mongodb.MongoClient.getDefaultCodecRegistry()).build();
MongoClient mgc= new MongoClient(servers,credentials,settings);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
