Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB "eval" order of execution

How using MongoDB shell define function and use it?

In a script file createusers.js there is following code to create a user with read role on specific database.

function createReader(database, username, password)
{
db.getSiblingDB(database).createUser({
    user  : username,
    pwd   : password,
    roles : [ { role : "read", db : database } ]
});
}

Is there possibility to execute this function in mongodb shell? The following call doesn't succeed

mongo --eval="createReader('somedb', 'user1', 'pass1')" createusers.js

gives error createReader is not defined.

like image 437
Developer Marius Žilėnas Avatar asked Dec 01 '25 20:12

Developer Marius Žilėnas


1 Answers

You can use load() to load the js file from eval:

mongo --eval "load('createusers.js'); createReader('somedb', 'user1', 'pass1')"
like image 78
mnemosyn Avatar answered Dec 04 '25 08:12

mnemosyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!