Is there any Java MongoDB library that supports executing native JSON aggregation queries? It seems that MongoTemplate from spring-data-mongo and even MongoClient all require some kind of Java abstraction. But I would like to simply store my queries in external file in JSON format and just execute them without any extra layer of abstraction so they can be simply reused. Similar to native SQL queries.
Add a comment
|
1 Answer
You can do that with MongoTemplate.
Here's an example of a Spring Repository :
@Autowired
private MongoTemplate mongoTemplate;
@PostConstruct
public void addMarketsToDB() {
if (mongoTemplate.findOne(new Query(), MarketEntity.class) == null) {
URL url = this.getClass().getResource("/marches.json");
byte[] encoded;
try {
encoded = Files.readAllBytes(Paths.get(url.toURI()));
BasicDBObject obj = new BasicDBObject();
obj.append("$eval", new String(encoded));
mongoTemplate.executeCommand(obj);
} catch (IOException | URISyntaxException e) {
LOGGER.error("{} addMarketsToDB -> failed to read file", LOG_HEADER);
}
}
}