How do I execute a MongoDB js script using the Java MongoDriver

前端 未结 4 751
刺人心
刺人心 2020-12-10 17:00

I have implemented a JavaScript function inside the Mongodb server using this example.

It works fine when I use mongo shell, but I want to run it from inside a Java

相关标签:
4条回答
  • 2020-12-10 17:44

    You should use DB.eval(), see the api docs and make sure that you don't do string concatenation. Pass the variables through instead.

    I think your answer is probably the same answer as this other one on StackOverflow.

    0 讨论(0)
  • 2020-12-10 17:49
    @Autowired
    private MongoOperations mongoOperations;
    
    private final BasicDBObject basicDBObject = new BasicDBObject();
    
    @PostConstruct
    private void initialize() {
        basicDBObject.put("eval", "function() { return db.loadServerScripts(); }");
        mongoOperations.executeCommand(basicDBObject);
    }
    
    private void execute() {
        basicDBObject.put("eval", "function() { return echoFunction(3); }");
        CommandResult result = mongoOperations.executeCommand(basicDBObject);
    }
    

    And then you can use something like:

    ObjectMapper mapper = new ObjectMapper();
    

    And MongoOperation's:

    mongoOperations.getConverter().read(CLASS, DBOBJECT);
    

    Just try to have some workaround depends on your requirements

    0 讨论(0)
  • 2020-12-10 17:51

    The previous answers does not work in MongoDB 3.4+. Th proper way to do this in version 3.4 and above is to create a BasicDBObject and use it as the parameter of Database.runCommand(). Here's an example.

    final BasicDBObject command = new BasicDBObject();
                command.put("eval", String.format("function() { %s return;}}, {entity_id : 1, value : 1, type : 1}).forEach(someFun); }", code));
                Document result = database.runCommand(command);
    
    0 讨论(0)
  • 2020-12-10 17:55

    Since MongoDB 4.2 the eval command is removed (it was deprecated in 3.0). There is no more way to eval JavaScript scripts into MongoDB from the Java Driver.

    See https://docs.mongodb.com/manual/reference/method/db.eval/

    0 讨论(0)
提交回复
热议问题