Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify which database to use in mongodb .js script

Tags:

I just want to run a .js script against a particular mongodb database, but can't seem to get the correct syntax.

echo "print(db.address.find().limit(1));" > test.js
mongo test.js

How do I select the database that this will be executed on, I've tried various combinations of use foo with no success.

> show dbs                      
admin   (empty)
local   (empty)
foo 0.203125GB
bar 0.203125GB

I would like to use foo in this case.

like image 692
markdsievers Avatar asked Jul 19 '11 19:07

markdsievers


People also ask

How do I select a database in MongoDB?

In MongoDB, you can use the show dbs command to list all databases on a MongoDB server. This will show you the database name, as well as the size of the database in gigabytes. You can select any database using the use statement and work on it.

How do I run a JS script in MongoDB?

Load JavaScript file js file from mongo shell, using the load() function. load() function allow to execute from absolute and relative paths. We can simply load a file in mongo shell with load() function. And Finally If we have lots of scripted files, We can load() inside another javaScript file.

Can you use MongoDB with JavaScript?

The MongoDB Node. js Driver allows you to easily interact with MongoDB databases from within Node. js applications. You'll need the driver in order to connect to your database and execute the queries described in this Quick Start series.


1 Answers

mongo <name of db> --eval "db.runCommand( <js in here> );"

Or if you dont have a specific runCommand script, you can just do:

mongo <name of db> --eval "<js in here>;"

If you are using a return value:

mongo <name of db> --eval "db.eval('return fnName()')"

For a file

mongo <name of db> some_instructions.js
like image 90
Chris Barretto Avatar answered Oct 12 '22 01:10

Chris Barretto