injecteer
injecteer

Reputation: 20699

Run script command/file in MongoDB Java

I search through the half of the Internet but found either nothing or outdated solutions with db.eval(). Hence my question.

I have some code using mongo driver 3.5.0:

MongoDatabase db = mongoClient.getDatabase 'mydb'
println db.runCommand( new BasicDBObject( eval:'db.version()' ) )

Exception in thread "main" com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on mydb to execute command { eval: "db.version()", $readPreference: { mode: "secondaryPreferred" }, $db: "mydb" }' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on mydb to execute command { eval: \"db.version()\", $readPreference: { mode: \"secondaryPreferred\" }, $db: \"mydb\" }", "code" : 13, "codeName" : "Unauthorized" } at com.mongodb.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:115) at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:107)

I can run this command in the shell:

mongo "mongodb://admin:admin@somehost:27003/mydb?replicaSet=myset" -eval 'db.version()'

outputs

3.6.6

If I run the command from inside the shell:

db.runCommand( { 'eval':'db.version()' } )

I'm also getting

{ "operationTime" : Timestamp(1536931496, 11), "ok" : 0, "errmsg" : "not authorized on mydb to execute command { eval: \"db.version()\", $db: \"mydb\" }", "code" : 13, "codeName" : "Unauthorized" }

The user I'm connecting with looks like:

{
    "_id" : "mydb.admin",
    "user" : "admin",
    "db" : "mydb",
    "roles" : [
            {
                    "role" : "readWrite",
                    "db" : "mydb"
            },
            {
                    "role" : "dbAdmin",
                    "db" : "mydb"
            },
            {
                    "role" : "userAdmin",
                    "db" : "mydb"
            },
            {
                    "role" : "dbOwner",
                    "db" : "mydb"
            }
    ]
}

What am I missing? Do I need special privileges for eval?

Upvotes: 0

Views: 1218

Answers (1)

chandra
chandra

Reputation: 500

As per mongodb documentation, you need a role that grants anyAction on AnyResource.

Upvotes: 1

Related Questions