How to execute/import JS file in Mongo Shell

You can write your code, json or logic in the javascript file and load it simply using load() method which takes absolute and relative path.

There are 2 ways :

#1 When you are in mongo shell use load and keep file in script folder

#2 When you are in terminal and want to load and connect to mongo shell
➜ mongo --shell myDatabaseName /Users/asee2278/myFile.js

MongoDB shell version: 3.0.6 connecting to:myDatabaseName
type “help” for help
> obj { “name” : “aseem” } >

Note : Please make sure to put only Js and not mongo commands other wise import might fail with message : E QUERY Error: error loading js file Another way is to file it from bash

bash$ mongo localhost:27017/test myjsfile.js

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.