Joey Yi Zhao
Joey Yi Zhao

Reputation: 42418

How to run a javascript file inside a mongo shell after connection

I have a javascript file and want to run them inside a mongo shell. I know how to load the javascript file during connection from this link: How to execute mongo commands through shell scripts?. But my case is how to run an external js file after the connection already established.

My js file looks like below:

db.getSiblingDB("test")
  .enron_messages.find({
    $or: [{ filename: "111." }, { "headers.From": "[email protected]" }]
  })
  .sort({ "headers.To": 1 })
  .limit(10);

and in my mongo shell, I use load('test.js') to load that file but it returns true(see below output). How to execute this file?

> load('test.js')
true

Upvotes: 0

Views: 6866

Answers (1)

helmy
helmy

Reputation: 9497

The load() function does in fact execute the javascript file. The problem you are facing is that when the external scripts are executed in "scripted" mode, find() will only return the cursor and not iterate it as the mongo shell does when run in Interactive mode.

This behavior is detailed in the docs in Write Scripts for the Mongo shell. There you will see an example of how you need to iterate the cursor and print the results:

cursor = db.collection.find();
while ( cursor.hasNext() ) {
    printjson( cursor.next() );
}

Upvotes: 3

Related Questions