I am trying to get a set of results based on the aggregate method of mongo and based on the return I am trying to add a property in all of them. The aggregate method provides me the highest no. of sales in a month from a particular outlet in a complex. I want to add a property highestSales to those documents which it returns. My query is:
var shops = db.data.aggregate([
{
$group: {
_id: "$shopName",
Sales: { $max: "$Sales" }
}
}
]);
The shops variable provides me 5 shop names as below:
{ "_id" : "Shop1", "Sales" : "$83,000" }
{ "_id" : "Shop2", "Sales" : "$69,000" }..
But when I am trying to loop through the shops it is not allowing me to add a new property. The reason I assume is that the shops is not an array of objects. Can anyone kindly inform what is the return type of the same?? Can this be achieved in any other way?
aggregate()
method returns a cursor to the documents produced by the final stage of the aggregation pipeline operation, or if you include the explain option, the document that provides details on the processing of the aggregation operation.
You need to add a toArray()
method to the shops variable or the resulting cursor from the aggregate()
method, e.g.
var shops = db.data.aggregate([
{
$group: {
_id: "$shopName",
Sales: { $max: "$Sales" }
}
}
]).toArray();
The toArray()
method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With