Running a JavaScript script within MongoDB

Seeking guidance on running a JavaScript file within MongoDB.

Here is a snippet of code from my JS file:

function loadNames() {
    print("name");
}

My attempt to execute the file from the command prompt:

mongo test.js

resulted in the following error:

unexpected identifier

Could someone please shed light on where I might be making a mistake?

Answer №1

My typical method for running test queries is similar to this, and I found success when using it with the sample code provided.

execute < test.js

Answer №2

There are two ways to accomplish this:

1. Utilize "--eval"

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

2. Run the JavaScript file

mongo data_db print.js

Here is the content of print.js:

printjson(db.getCollectionNames())

Answer №3

After running the command mongo --help, we found the following information:

$ mongo --help
MongoDB shell version v3.6.2
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
Options:
  --shell                             run the shell after executing files
  --nodb                              don't connect to mongod on startup - no 
                                      'db address' arg expected
  --norc                              will not run the ".mongorc.js" file on 
                                      start up
  --quiet                             be less chatty
  --port arg                          port to connect to
  --host arg                          server to connect to
  --eval arg                          evaluate javascript
  -h [ --help ]                       show this usage information
  ... ...

Furthermore, upon consulting MongoDB's documentation, we came across a script named my-mongo-script.js:

'use strict';

// @see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/

var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";

var db = connect(MONGODB_URI);

var collections = db.getCollectionNames();

print(collections.join('\n'));

printjson(collections);

Executing the command mongo --nodb my-mongo-script.js will run this script. To include the "--shell" option and run the shell after executing files, you can use

mongo --nodb --shell my-mongo-script.js
.

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

value assigned to ng-model does not update beyond its scope

My issue involves binding an ng-model to an input field. Despite this, the value of the variable it is connected to does not update outside of the specific div where the directive is defined: <div input-field ng-if="startTypes.selected.value == &a ...

Convert JavaScript back into an HTML attribute

Is there a way to include a JavaScript code in an HTML attribute like shown below? <div class="xx" animation="yy" animate-duration="<script>Code goes here<script>" ...> </div> I'm struggling to figure it out, is there a solut ...

Exploring the capabilities of nested ElemMatch in the MongoDB C# Driver

Given the structure below, how can I find zoos that have noisy animals? public class Zoo { public List<Cage> Cages { get; set; } } public class Cage { public List<Animal> Animals { get; set; } } public abstract class Animal { pub ...

Utilizing Express multer to save a variety of files to MongoDB from various form fields

https://i.stack.imgur.com/Wpyi0.pngI am currently facing an issue with uploading two image files to a database named "cast" using multer. When I input the images from a form, sometimes it accepts files from all input fields, but other times it only allows ...

Is there a way to convert various elements sharing the same class into a list of array items?

Essentially, I am dealing with multiple elements sharing the same class name. My goal is to retrieve an array of integers from an API and then iterate through each element with this class name, replacing them with elements from the array sequentially. For ...

Is it possible to implement CSS code from a server request into a React application?

With a single React app that hosts numerous customer websites which can be customized in various ways, I want to enable users to apply their own CSS code to their respective sites. Since users typically don't switch directly between websites, applying ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Creating a PDF from dynamic HTML and transferring it to an AWS S3 bucket without the need to download the PDF

We have created a web application using React JS where we attempted to generate a PDF. Instead of downloading or opening the PDF in a new window, our goal is to directly upload it to an AWS S3 bucket. We have researched and tried various samples but have n ...

Is there a way for me to modify the formatting of the text that I

Can you help me transform a text that looks like this: '?category=1,2&brand=1' into something like this: '?categories[]=1&categories[]=2&brands[]=1'? I'm not quite sure how to make this change. ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Generate SVG components without displaying them

Is there a way to generate a custom SVG graphic through a function without the need to attach it to any element? Can I simply create an empty selection and return that instead? Here is my current implementation: function makeGraphic(svgParent) { retur ...

Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently w ...

Utilize a MongoDB query to locate a single document and include a conditional statement within the update operation

I've been struggling with this problem for quite some time now and I could really use some guidance from experts here on SO. Essentially, what I am trying to achieve is to locate a specific document using a provided _id, and then execute a conditional ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file. Here is an example of my JSON data: {"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlin ...

Passing a jQuery dialog variable for use in a php function using ajax

I am struggling to successfully pass variables from jQuery to a PHP function using AJAX. I have included the necessary HTML and script, but I'm confused as to whether the PHP file specified in the "url:" parameter should be external or can it be follo ...

Updating a MongoDB value by fetching the result of a query executed on a different collection

Is there a way to update the field of a collection by picking a value from another collection based on the existing field value? Here is what I have tried so far: db.Organizations.find({}).forEach( function(doc) { print(doc.Country.DisplayName); ...

Collapse the hamburger menu upon clicking on a link in the mobile menu

Whenever I click on a menu item, the page loads but the menu remains open. This JSX code represents the Mobile Menu: const MobileMenu = () => { const navigation = [ { link: '/applications', text: 'Applications' }, { link ...