Push query results into variable with MongoDB?


For this, you can use aggregate(). Let us create a collection with documents −

> db.demo142.insertOne({"Value":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9c6fdf09dd6d08539b2")
}
> db.demo142.insertOne({"Value":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9cafdf09dd6d08539b3")
}
> db.demo142.insertOne({"Value":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9cdfdf09dd6d08539b4")
}
> db.demo142.insertOne({"Value":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9d0fdf09dd6d08539b5")
}
> db.demo142.insertOne({"Value":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32e9d9fdf09dd6d08539b6")
}

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

> db.demo142.find();

This will produce the following output −

{ "_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 }

Following is the query to push query results into variable −

> var query = db.demo142.aggregate( 
...    { "$group": { "_id": null, "MaxValue": { "$max": "$Value" } } }
... ]);
> var largestValue= query.toArray()[0]["MaxValue"];
> printjson(largestValue);

This will produce the following output −

60

Updated on: 31-Mar-2020

685 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements