12

I am newbie to mongodb.

We can execute list of queries by specifying it in a script .sql file in relational db and can run it by running the command source c:\test.sql.

How can we do that in mongodb? how to store those commands in mongodb script and how to execute in mongodb?

0

2 Answers 2

21

You can do it with shell script. You can execute the commands using the following command.

./mongo server:27017/dbname --quiet my_commands.js

For details check Scripting the shell document in Mongo docs.

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

1 Comment

0

Not sure if the answer is just too old, or there are different ways to do it. Well theoretically the answer specifies a '.js' file but tells about "can do it with shell script".

Anyways, I guess could be that now there is better documentation, but here another way to do it

How to store those commands in mongodb script?

I think the question is also really "Which file type/extension should be use to create mongo script files"

Using Javascript (no need any type of library just mongosh)

Example

db = connect( 'mongodb://localhost/sandbox' );
console.log(db);
console.log(Object.keys(db));

How can we do that in mongodb?

From the mongosh shell use the load command with an absolute or relative path to the script.

Example

Assuming we are using linux do the following

mkdir mongo_sandbox
cd mongo_sandbox
touch mongo_script.js

Now let's create a mongo Javascript script, you know use vim, VSCode, pen and paper.. whatever

db = connect( 'mongodb://localhost/myDatabase' );
db.movies.insertMany( [
   {
      title: 'Titanic',
      year: 1997,
      genres: [ 'Drama', 'Romance' ]
   },
   {
      title: 'Spirited Away',
      year: 2001,
      genres: [ 'Animation', 'Adventure', 'Family' ]
   },
   {
      title: 'Casablanca',
      genres: [ 'Drama', 'Romance', 'War' ]
   }
] )

let movies = db.movies.find();

console.log(movies);

Cool now, lunch mongosh

mongosh sandbox
# ...bla bla bla 
sandbox>

Run the script

load( "./mongo_script.js" )

Which outputs

sandbox> load( "./mongo_script.js" )
[
  {
    _id: ObjectId("64e8560e2932f758ce7d11a3"),
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ]
  },
  {
    _id: ObjectId("64e8560e2932f758ce7d11a4"),
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ]
  },
  {
    _id: ObjectId("64e8560e2932f758ce7d11a5"),
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ]
  }
]
true

Documentation

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.