Jessie
Jessie

Reputation: 1105

mongodb script file

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.

For instance

CREATE DATABASE `sandbox`;
USE `sandbox`;

CREATE TABLE pet (
    name VARCHAR(20), 
    owner VARCHAR(20),
    species VARCHAR(20), 
    sex CHAR(1), 
    birth DATE, 
   death DATE
);
SHOW TABLES;

Then it can be execute as

$ mysql -u root -p admin
mysql > source test.sql;

Questions

Upvotes: 13

Views: 15708

Answers (2)

Federico Baù
Federico Baù

Reputation: 7636

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

Upvotes: 0

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

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.

Upvotes: 21

Related Questions