Is there a way to execute a standalone JavaScript file using the Mongo Shell?

While MongoDB has a Node.js driver and allows using JavaScript code for commands, is there a way to directly run a JavaScript file without relying on the Node.js driver? For instance: mongo somejavascriptfile.js, and use it to interact with databases as needed? Assuming that somejavascriptfile.js contains content similar to this.

use companies;
show collections;

db.myCollection.insertOne({name: "New Company", location: "Nice Location"});

Answer №1

Latest Update

Click here for more information on using the --eval option in MongoDB shell scripts.

Utilize the --eval option when running scripts in the mongo shell by passing a JavaScript fragment as shown below:

mongo test --eval "printjson(db.getCollectionNames())"

Method 1:

// script1.js

db.myCollection.insertOne({name: "New Company1", location: "Nice Location"})
// execute
mongo myDB script1.js

Method 2:

// script2.js
db.getSiblingDB('companies').myCollection.insertOne({name: "New Company", location: "Nice Location"});
db.getSiblingDB('companies1').myCollection.insertOne({name: "New Company", location: "Nice Location"});
db.getSiblingDB('companies3').myCollection.insertOne({name: "New Company", location: "Nice Location"})
// run
mongo script2.js

Yes, you can run the script somejavascriptfile.js like this

mongo myDB somejavascriptfile.js // on a specific databse

mongo somejavascriptfile.js

Learn more about the --eval option in the MongoDB documentation.

--eval Evaluates a JavaScript expression that is specified as an argument. mongo does not load its own environment when evaluating code. As a result, many options of the shell environment are not available.

mongo myDB --eval "var myVar = 'testVar'" somejavascriptfile.js // pass some variables to your script

Additionally, check out

This link provides information on how to load and run a JavaScript file in the MongoDB shell environment.

The load() method has the following parameter:

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

Answer №2

In addition to the answer provided, you have several options for executing the command:

echo 'db.myCollection.insertOne({name: "New Company1", location: "Nice Location"})' | mongo myDB

mongo myDB <<< 'db.myCollection.insertOne({name: "New Company1", location: "Nice Location"})'

mongo myDB <<EOF
use companies;
show collections;
db.myCollection.insertOne({name: "New Company", location: "Nice Location"});
EOF

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for Vue Router to remember the scroll position on a route and return to the same position when navigating back?

My Vue Router is not saving the scroll position and always loads at the top of the page (0, 0). Any suggestions on what could be causing this issue? Here is my current router code setup: const scrollBehavior = (to, from, savedPosition) => { if (saved ...

Adding six months to a particular field in all documents in MongoDB

I have a collection named Articles and each article contains a field called publication_date structured like this: "publication_date" : ISODate("2020-02-10T00:00:00Z") My goal is to update all articles by adding 6 months to their exist ...

Express Route Handler doesn't work for specific file types

I am currently working on setting up a route handler for requests to '.js' files. I have successfully configured middleware to serve static files from a "/dist" directory, which is functioning correctly. However, I am facing an issue where the r ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

Is there a way to determine the names of the functions that are being called?

I'm working on mastering Google Development Tools. Is there a way to determine which specific functions, especially those in Javascript, are needed before a page can load successfully? ...

What is the best way to programmatically close a bootstrap modal?

Currently, I am performing update operations through a modal. When the modal pops up, it loads specific row data that I intend to update. Here is the code for my modal: <form id="form1" runat="server"> <asp:ScriptManager ID="sm1" runat="serve ...

Unexpected Website Homepage (Vue / Javascript)

I am looking to display a different .vue file each time a visitor refreshes the Home page. Currently, I only have one page called Home.vue. I am attempting to randomly load either Home1.vue or Home2.vue with each refresh. { path: '/', name: ...

What is the best approach to animating a specified quantity of divs with CSS and javascript?

How neat is this code snippet: <div class="container"> <div class="box fade-in one"> look at me fade in </div> <div class="box fade-in two"> Oh hi! i can fade too! </div> <div class="box fade-in three"& ...

Determining the Presence of a Specific Document in MongoDB

Let's say I have a collection called Posts, and I am interested in determining whether my Posts collection contains a specific document. For instance: Posts = new Mongo.Collection('posts'); Posts.insert({ name: "John", ....etc. )}; va ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

Unable to decrease the width of a div element in Vuetify and Nuxt

As I work on creating a dynamic form with fields that need to occupy only 50% of the size of a regular field, I encounter different components based on data provided by Vuex. The use of v-for in Vue.js helps me loop through form objects and render the app ...

How can I extract the reference link of a hyperlink within a specific division and use it for an image?

I currently have a div containing an image and a link. Is it feasible for me to find the href of the link on page load and then apply it to the anchor tag of the image? I understand this may sound like an unusual request, but I'm just curious if it& ...

Attempting to test a Jasmine directive in Angular results in failure

After creating a simple directive that throws an error when the input is invalid, I encountered an issue with my testing. When attempting to test for the thrown error using expect().toThrow(), it succeeded as expected. However, the same result occurred w ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

After refreshing the page, the JQuery radio button will still be selected

In my form, a radio button triggers an additional text field based on user selection. To achieve this functionality, I am using the following jQuery script: $(document).ready(function(){ $('input:radio[name="accountType"]').change(function() ...

Locate documents where the field is present or empty

My documents are structured like this: { "...": ... "validated_at": null "archived_at": null "..." : ... } I am searching for all documents where validated_at is null AND archived_at is null OR not present in the do ...

An adhesive feature that halts upon reaching a specific element

Can anyone help me create a fixed element that behaves like a sticky element when scrolling and reaches the top of another specified element? I want this fixed element to stay within the boundaries of the element I set as the "ground", preventing it from p ...

Prevent Importing Folders Without Index Using ESLint Rule or VS Code Setting

Query: Are there any ESLint rules that can be applied to enforce the utilization of */index in imports? Illustration: Directory setup: utils/ - index.js - a.js - b.js main.js main.js // INCORRECT import utils from "./utils"; // CORR ...

Adaptable Image Functionality in Jquery Carousel

I've encountered an issue with my images within a jquery slider. While the slider itself is functioning properly, I am facing a couple of challenges. Initially, I aimed to make the images responsive, but upon removing the height property, the content ...

Tips for transmitting div id through Ajax without using a form

I'm attempting to capture the ID of the clicked element and pass it to a PHP page without using a form. Although everything seems to be working fine, I'm facing an issue where no data is being sent to the PHP page. Despite checking the code in t ...