Divyang Desai
Divyang Desai

Reputation: 7866

How to call MongoDB commands using .bat file

I'm trying to execute MongoDB command (for create DB) using .bat file.

For that I've tried:

cd C:\Program Files\MongoDB\Server\3.4\bin
mongo 
mongo --eval "use MyDatabase"
pause

But it gives an error missing ; before statement @(shell eval):1:4
How can I solve this issue?

Side: I've already gone through MongoDB SyntaxError: missing ; before statement @(shell)

Upvotes: 8

Views: 15187

Answers (3)

Rishav Singh
Rishav Singh

Reputation: 343

Try this:

cd C:\Program Files\MongoDB\Server\3.4\bin
mongo.exe 
mongo.exe --eval "use MyDatabase"
pause

or use a text file script.txt containing your commands and write batch file as:

cd C:\Program Files\MongoDB\Server\3.4\bin
mongo.exe mydb < script.txt

can use full path if file is at different location.

Upvotes: 0

Sparw
Sparw

Reputation: 2743

Can you try with :

cd Program Files\MongoDB\Server\3.4\bin
mongo.exe 
mongo.exe --eval "use MyDatabase"
pause

I am using a .bat file which works properly and contains this

cd \Program Files\MongoDB\Server\3.2\bin
mongod.exe
pause

EDIT

I tested a file like this and it works fine (create db, collection and document)

mongodb.bat

cd \Program Files\MongoDB\Server\3.2\bin
mongo.exe db-mydb --eval "db.yourCollection.insert({key:'value'});"
pause

EDIT 2

If you want to run your .bat file on the background, i have made a .VBS file which works properly

mongodb.VBS

Set WshShell = CreateObject("WScript.Shell") 
WshShell.Run chr(34) & "C:\Path\To\Your\mongodb.bat" & Chr(34), 0
Set WshShell = Nothing

Hope it helps

Upvotes: 11

Tzvi Gregory Kaidanov
Tzvi Gregory Kaidanov

Reputation: 3140

  • Put this code in your bat file.
  • It'll start and activate the mongodb in 2 different admin privileged cmd windows.
  • Please check the paths before to adjust to your environment.

START "runas /user:administrator" cmd /K "cd C:\Program Files\MongoDB\Server\3.4\bin & mongod.exe --dbpath c:\data\db"

TIMEOUT /T 10 START

START "runas /user:administrator" cmd /K "cd C:\Program Files\MongoDB\Server\3.4\bin & mongo.exe "

Upvotes: 3

Related Questions