Viewing the data returned by the load() function in MongoDB within a commandline session

Currently, I am utilizing MongoDB through the command line on a linux system.

I have created a simple deletedata.js script which appears as follows;

//this script deletes everything
db.Collection1.deleteMany({})
db.Collection2.deleteMany({})
db.CollectionN+1.deleteMany{}

In order to delete all data from multiple collections at once, I manually log in to MongoDB using the standard login command;

mongo 'hostname'/mongodb_name --username myusername --password mypassword

Once logged into MongoDB, I execute the script using the command;

load('/home/username/deletedata.js')

The script runs successfully and all the deleteMany commands are executed. However, the only output I receive is "true".

Although I am comfortable with writing MongoDB commands, I am limited to that skill set. I am curious if it is possible to enhance the script with additional MongoDB commands and display the output within the MongoDB session on the command line?

For example, when trying to add a count() command like;

db.Collection1.find({}).count()

After running the script again using;

load('/home/username/deletedata.js')

I still only see "true" returned. How can I show the output of the count() command when it is included in the .js file and executed within MongoDB using load()?

I anticipated that the result of the mongodb .count() command would be displayed on the mongoDb command line, but the only output I get when using the mongoDb load('') command is "true" if the script runs.

Answer №1

Give this a shot:

let result = db.Collection1.deleteMany({})
print(result)
// Alternatively
print(tojsononeline(result))

let count = db.Collection1.find({}).count()
print(count)

If you are utilizing the latest mongosh version, make sure to either load mongocompat, or use print(EJSON.stringify(result))

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

Error: The selector "html" is not considered pure as it does not contain any local class or id. Pure selectors must include at least one local class or id

When working on my Next.js project, I included the following code in _app.js: import '../src/styles/style.module.scss'; import '../src/styles/main.module.scss'; This is the content of main.module.scss: // ./src/styles/main.module.scss ...

Leveraging the power of the wildcard feature to execute a variety of scripts when running

Inside my package.json file, I currently have the following scripts block: "scripts": { "test": "node tests/*-test.js" } In the tests folder, I have files named a-test.js and b-test.js. This can be confirmed by using the command ls tests/*-test.js. ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

The Three.js raycaster is already picking up on objects before I even start moving the mouse

I'm experimenting with the Three.js raycaster and have created a grid of planes that are supposed to start off yellow and turn red when you hover over them with the mouse. However, the issue I'm facing is that when I run the script, all the plane ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

Error: Latitude and longitude of boundary points

Trying to extract points within a polygon using the query below: loc: { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [ [ [ -117.83736, 33.73838 ...

Difficulty locating information in MongoDB using Node.js

When attempting to retrieve data from a mongo database, the entire object with all properties including _id and title is returned. However, I only require the title. How can I resolve this? Models and Mongo Schema const mongoose = require('mongoose& ...

Unable to enclose an element with an HTML structure

I am attempting to take all the elements marked with the table tag and envelop them in an HTML structure to make the tables responsive. However, it appears that my current approach is not yielding the desired results. Can you please provide some insight ...

What is the best way to create a flexible canvas/grid/row/column that can adapt to changes in browser width and height, all while maintaining its aspect ratio

As someone new to the world of JavaScript, CSS, and HTML, I am eager to learn how to create a game site with multiple games. However, I am feeling lost when it comes to determining the right direction to take. My goal is to develop a game board that can ad ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

Asynchronous setTimeout for server-side operations

I am currently facing an issue with my web server. Whenever a request is made, the server initiates a phone call, waits for 3 seconds, and then checks if the call is still ongoing. I have utilized setTimeout to achieve this functionality, but it seems to b ...

Troubleshooting Issues with jQuery Accordion Buttons

I have a nearly complete accordion that just needs some adjustments. HTML CODE: <footer> <div> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> ...

How can we stop the anchor jump caused by a third-party script?

I'm currently utilizing a third-party script (details provided below) to divide a form into multiple ajax'd pages. However, when I attempt to move on to the next page, it immediately jumps to an anchor at the top of the form. This behavior is unn ...

What is the best way to attach an event listener to a div so that clicking on it increases the width and height of the div by 20%?

I've started working on it and decided to use the same dimensions (100px by 100px) as a previous question. Right now, I'm sticking with just Javascript, but I might incorporate jQuery down the line. One big issue is that in the line (this.style.w ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

Is it possible to utilize jQuery to add 'a' attributes in HTML5?

Here is a snippet of code that works with Chrome and Firefox browsers: HTML: <a id="savefile""> Save transferred file </a> Javascript: // event is returned by a readAsDataURL() var save = document.getElementById('savefile'); s ...

Issue with typography upon initial page load

Hey everyone! I recently completed a crash course in html, css, and javascript within just one month. However, I encountered an issue while using canvas to draw text with a custom font. The font didn't load the first time I ran the code, but strangely ...

Executing JavaScript code does not execute CSS code

Having some trouble with my Javascript and CSS. The script is functioning well, but when I use the filtering function, the CSS stops working and only the filtered results are displayed on the HTML page. Looking for advice on how to fix the Javascript. & ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

Implementing complex routing with Express.js on top of Node.js

Recently delving into the world of javascript, I have embarked on creating a RESTful API using Node.js and Express.js Here is the breakdown of my directory structure: /server.js /api/api.js /api/location/location.js My goal is to make the API modular, ...