Run javascript script (.js file) in mongodb including another file inside js
Asked Answered
W

5

72

I want to write a long script for inserting and updating mongodb data.

  1. Is it possible to call external js file that contains the script?
  2. Is it possible to include another js file from the running js file?
Worldbeater answered 7/3, 2014 at 11:21 Comment(0)
P
128

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2
Protean answered 7/3, 2014 at 11:29 Comment(2)
More info can be found here: docs.mongodb.org/manual/tutorial/…Bracteate
yosh looking for this, i first thought i should execute some restore commandTel
C
13

Another way is to pass the file into mongo in your terminal prompt.

$ mongo < myjstest.js

This will start a mongo session, run the file, then exit. Not sure about calling a 2nd file from the 1st however. I haven't tried it.

Circumspection answered 30/10, 2018 at 18:42 Comment(0)
D
8

Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")
Diminish answered 27/3, 2015 at 7:44 Comment(0)
P
1

for running mutilple js files

#!/bin/bash
cd /root/migrate/

ls -1 *.js | sed 's/.js$//' | while read name; do
     start=`date +%s`
     mongo localhost:27017/wbars $name.js;
     end=`date +%s`
     runtime1=$((end-start))
     runtime=$(printf '%dh:%dm:%ds\n' $(($runtime1/3600)) $(($secs%3600/60)) $(($secs%60)))
     echo @@@@@@@@@@@@@ $runtime $name.js completed @@@@@@@@@@@
     echo "$name.js completed"
     sync
     echo 1 > /proc/sys/vm/drop_caches
     echo 2 > /proc/sys/vm/drop_caches
     echo 3 > /proc/sys/vm/drop_caches
done
Polak answered 1/2, 2019 at 6:29 Comment(1)
I got this error: ./install.sh: line 9: %3600/60: syntax error: operand expected (error token is "%3600/60")Hardesty
H
1

To call external file you can use :

load ("path\file")

Exemple: if your file.js file is on your "Documents" file (on windows OS), you can type:

load ("C:\users\user_name\Documents\file.js")

Halakah answered 15/11, 2019 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.