Docs Menu

Write Scripts for mongosh

On this page

You can write scripts for the MongoDB Shell that manipulate data in MongoDB or perform administrative operations. You may also want to package your scripts as snippets for easier distribution and management.

This tutorial introduces using the MongoDB Shell with JavaScript to access MongoDB.

From the MongoDB Shell or from a JavaScript file, you can instantiate database connections using the Mongo() method:

new Mongo()
new Mongo(<host>)
new Mongo(<host:port>)
Note

The MongoDB Shell does not support the ClientSideFieldLevelEncryptionOptions document with the Mongo() method.

Consider a MongoDB instance running on localhost on the default port.

The following example:

  • Instantiates a new connection to the instance, and
  • Sets the global db variable to myDatabase using the Mongo.getDB() method.
conn = Mongo();
db = conn.getDB("myDatabase");

To connect to a MongoDB instance that enforces access control, you must include the credentials in the connection string.

The following command connects to a MongoDB instance that is:

  • Running on localhost on the default port, and
  • Secured using SCRAM.
conn = Mongo("mongodb://<username>:<password>@localhost:27017/<authDB>");
Note

The MongoDB Shell redacts credentials from the command history and the logs.

You can also use the connect() method to connect to the MongoDB instance.

The following command:

  • Connects to the MongoDB instance that is running on localhost with the non-default port 27020, and
  • Sets the global db variable.
db = connect("localhost:27020/myDatabase");

Consider portability and the operating environment when you write scripts.

If the connection details are included in the script:

  • You do not need to specify connection information on the command line.
  • You should use the --nodb parameter.

Consider a mongod instance running on localhost:27500.

The following script prints the number of users. Copy the code and save it as getUserCount.js.

db = connect( "localhost:27500/admin" );˘
printjson( db.system.users.countDocuments() );

Run getUserCount.js:

mongosh --nodb --file getUserCount.js
  • mongosh defaults to port 27170.
  • mongod is running on port 27500.
  • The --nodb parameter instructs mongosh to run a script without first connecting to a mongod instance.

The highlighted line is correct, but getUserCount.js will not run without --nodb because mongosh cannot connect to the local instance. With --nodb, mongosh runs getUserCount.js and uses the highlighted information to connect.

It is convenient to specify connection information in your script, but that also makes it less portable. The getUserCount.js script would have to be updated to run on a remote instance or one running on a different port.

To increase portability, use db.getSiblingDB() and specify the connection information on the command line.

The following script is more portable than getUserCount.js because it does not have specific connection details. Copy the code and save it as portableGetUserCount.js.

db = db.getSiblingDB( "admin" );
printjson( db.system.users.countDocuments() );

To run portableGetUserCount.js, specify the host and port on the command line:

mongosh --host 172.17.0.3 --port 27500 --file portableGetUserCount.js

To run portableGetUserCount.js on a different host or port, change the connection details on the command line. Unlike getUserCount.js, you do not have to edit the script to run portableGetUserCount.js.

You can execute a .js file from within the MongoDB Shell using the load() method.

Example

The following example creates and executes a script that:

  • Connects to a local instance running on the default port.
  • Connects to the myDatabase database.
  • Populates the movies collection with sample documents.
  1. Create a file named connect-and-insert.js with the following contents:

    db = connect( 'mongodb://localhost/myDatabase' );
    db.movies.insertMany( [
    {
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ],
    rated: 'PG-13',
    languages: [ 'English', 'French', 'German', 'Swedish', 'Italian', 'Russian' ],
    released: ISODate("1997-12-19T00:00:00.000Z"),
    awards: {
    wins: 127,
    nominations: 63,
    text: 'Won 11 Oscars. Another 116 wins & 63 nominations.'
    },
    cast: [ 'Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates' ],
    directors: [ 'James Cameron' ]
    },
    {
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ],
    rated: 'PG',
    languages: [ 'Japanese' ],
    released: ISODate("2003-03-28T00:00:00.000Z"),
    awards: {
    wins: 52,
    nominations: 22,
    text: 'Won 1 Oscar. Another 51 wins & 22 nominations.'
    },
    cast: [ 'Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki', 'Takashi Naitè' ],
    directors: [ 'Hayao Miyazaki' ]
    },
    {
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ],
    rated: 'PG',
    cast: [ 'Humphrey Bogart', 'Ingrid Bergman', 'Paul Henreid', 'Claude Rains' ],
    languages: [ 'English', 'French', 'German', 'Italian' ],
    released: ISODate("1943-01-23T00:00:00.000Z"),
    directors: [ 'Michael Curtiz' ],
    awards: {
    wins: 9,
    nominations: 6,
    text: 'Won 3 Oscars. Another 6 wins & 6 nominations.'
    },
    lastupdated: '2015-09-04 00:22:54.600000000',
    year: 1942
    }
    ] )
  2. To load and execute the connect-and-insert.js file, run the following command from mongosh:

    load( "connect-and-insert.js" )
  3. To confirm that the documents loaded correctly, use the myDatabase collection and query the movies collection.

    use myDatabase
    db.movies.find()

The load() method accepts relative and absolute paths. If the current working directory of the MongoDB Shell is /data/db, and connect-and-insert.js is in the /data/db/scripts directory, then the following calls within the MongoDB Shell are equivalent:

load( "scripts/connect-and-insert.js" )
load( "/data/db/scripts/connect-and-insert.js" )
Note

There is no search path for the load() method. If the target script is not in the current working directory or the full specified path, the MongoDB Shell cannot access the file.

You can use mongosh to execute a script from the command line without entering the mongosh console.

Use the --file or -f parameters to specify the filename.

mongosh --port 27500 --file addMovies.js
Tip

If you pass a filename to mongosh without using the parameter flags the connection may fail if there are other command line arguments.

To pass filenames always use --file or -f.

You may also need to specify connection information in addition to the --file or -f parameters.

Example

The following example creates scripts and runs them from the command line.

  1. Copy this script and save it as loadMovies.js.

    db = connect( 'mongodb://localhost/films' );
    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' ]
    }
    ] )
    Tip

    Verify the connection string in the highlighted line. If your MongoDB instance is not running on localhost:27017, you must edit the connection string.

    db = connect( 'mongodb://localhost:27500/films' );

    This connection string is for the:

    • films database
    • located on localhost
    • listening on port 27500
  2. Copy this script and save it as queryMovies.js.

    db = connect( 'mongodb://localhost/films' );
    printjson( db.movies.find( {} ) );
  3. Run the scripts from the command line.

    mongosh --file loadMovies.js -f queryMovies.js
  4. Verify the output.

    Loading file: loadMovies.js
    Loading file: queryMovies.js
    [
    {
    _id: ObjectId("616f1b8092dbee425b661117"),
    title: 'Titanic',
    year: 1997,
    genres: [ 'Drama', 'Romance' ]
    },
    {
    _id: ObjectId("616f1b8092dbee425b661118"),
    title: 'Spirited Away',
    year: 2001,
    genres: [ 'Animation', 'Adventure', 'Family' ]
    },
    {
    _id: ObjectId("616f1b8092dbee425b661119"),
    title: 'Casablanca',
    genres: [ 'Drama', 'Romance', 'War' ]
    }
    ]

    The output of the db.collection.find() command shows that the movies collection was updated.

    Tip

    To make the output visible, use printjson() to call db.collection.find().

    printjson( db.movies.find( {} ) ) ;

To execute a script against a remote mongod instance that requires authentication, specify the connection and authentication details in addition to the filename.

The following lines are equivalent.

mongosh --host 172.17.0.3 --port 27500 --username filmFan --password superSecret --file loadMovies.js
mongosh --host 172.17.0.3 --port 27500 -u filmFan -p superSecret -f loadMovies.js
Tip

In shells like bash and zsh, if you begin a command with a space it will not be saved in your command history. This minimizes exposure if you enter passwords on the command line.

Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.