2

I am trying to run MongoDB queries from batch script in windows... I can not find any reference how to do that. Please can you show me some sample commands and one more question.

I am running this command for changing the database...

mongo --eval "use Sample_Test"

It does not work.

when I am inserting some data. It works, but, inserts in the default database, test.

mongo --eval "db.restaurants.insert({'Name':'Vishal'})"

I want to insert data in Sample_Test Database.

I only know above "mongo --eval" command, if anybody knows some more, please share it.....it would really help.

3 Answers 3

3

The data is getting inserted to default database as your use DB is not working here. You need to add database name here using -d if you are using older version of MongoDB like following :

mongo -d Sample_Test --eval  "db.restaurants.insert({'Name':'Vishal'})"

or you can execute any script file which contains all your mongo script like following:

mongo -d Sample_Test --eval mongoScript.js

In Mongo version 3.2, -d flag is not needed. For more information about script refer documentation

So you can simply use

mongo Sample_Test --eval "db.restaurants.insert({'Name':'Vishal'})"

Hope this will work for you.

Sign up to request clarification or add additional context in comments.

1 Comment

With mongo version 4 you do not include the --eval when running a script file : mongo localhost:27017/test myjsfile.js
0

use this code on place of your code:

mongo.exe Sample_Test --eval  "db.restaurants.insert({'Name':'Vishal'})"

but if you want to run multiple commands in one session login use script file.

Comments

0

You can also use the URL style to connect to a MongoDb server and database like:

mongo "mongoldb://localhost:8000/myCars" --eval "db.getCollection('restaurants').insert({'Name':'Vishal'})

You can also put credentials into the URL.

See: https://docs.mongodb.com/manual/mongo/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.