Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
