0

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.

1 Answer 1

0

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);
            }

        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.