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
Push query results into variable with MongoDB?
To push query results into a variable in MongoDB, use the aggregate() method combined with toArray() to store the result in a JavaScript variable. This technique is useful for storing intermediate results for further processing.
Syntax
var queryResult = db.collection.aggregate([
{ $group: { "_id": null, "fieldName": { "$operation": "$field" } } }
]);
var variableName = queryResult.toArray()[0]["fieldName"];
Sample Data
db.demo142.insertMany([
{"Value": 50},
{"Value": 45},
{"Value": 60},
{"Value": 55},
{"Value": 50}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e32e9c6fdf09dd6d08539b2"),
ObjectId("5e32e9cafdf09dd6d08539b3"),
ObjectId("5e32e9cdfdf09dd6d08539b4"),
ObjectId("5e32e9d0fdf09dd6d08539b5"),
ObjectId("5e32e9d9fdf09dd6d08539b6")
]
}
Display Documents
db.demo142.find();
{ "_id": ObjectId("5e32e9c6fdf09dd6d08539b2"), "Value": 50 }
{ "_id": ObjectId("5e32e9cafdf09dd6d08539b3"), "Value": 45 }
{ "_id": ObjectId("5e32e9cdfdf09dd6d08539b4"), "Value": 60 }
{ "_id": ObjectId("5e32e9d0fdf09dd6d08539b5"), "Value": 55 }
{ "_id": ObjectId("5e32e9d9fdf09dd6d08539b6"), "Value": 50 }
Example: Store Maximum Value in Variable
Find the maximum value and store it in a JavaScript variable ?
var query = db.demo142.aggregate([
{ "$group": { "_id": null, "MaxValue": { "$max": "$Value" } } }
]);
var largestValue = query.toArray()[0]["MaxValue"];
printjson(largestValue);
60
How It Works
-
aggregate()returns a cursor object containing the aggregation results -
toArray()converts the cursor to an array of documents -
[0]accesses the first (and only) document in the result -
["MaxValue"]extracts the specific field value
Conclusion
Use aggregate().toArray()[0]["fieldName"] to store query results in variables. This approach works with any aggregation operation and allows you to use the results in subsequent MongoDB operations or JavaScript logic.
Advertisements
