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

前端 未结 5 524
攒了一身酷
攒了一身酷 2020-12-24 10:14

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 pos
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 11:07

    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
    

提交回复
热议问题