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
load("scripts/myjstest.js")
load("/data/db/scripts/myjscript.js")

#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