Use result from MongoDB in shell script?

To use MongoDB query results in shell scripts, you can store the result in a JavaScript variable using the var keyword and then manipulate or access the data as needed.

Syntax

var variableName = db.collection.findOne(query, projection);
variableName.fieldName

Sample Data

Let us first create a collection with a document ?

db.useResultDemo.insertOne({"StudentFirstName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda70f5b50a6c6dd317adcd")
}

Display all documents from a collection with the help of find() method ?

db.useResultDemo.find();
{ "_id" : ObjectId("5cda70f5b50a6c6dd317adcd"), "StudentFirstName" : "Robert" }

Example: Store Query Result in Variable

Here is the query to use result from MongoDB in shell script with var keyword ?

var studentName = db.useResultDemo.findOne({}, {_id:0});
studentName
{ "StudentFirstName" : "Robert" }

Accessing Specific Fields

You can access specific fields from the stored result ?

var studentName = db.useResultDemo.findOne({}, {_id:0});
studentName.StudentFirstName
Robert

Conclusion

Using the var keyword allows you to store MongoDB query results in JavaScript variables within the shell. This enables you to manipulate data, access specific fields, and perform additional operations on the retrieved results.

Updated on: 2026-03-15T00:53:07+05:30

596 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements