THE ISSUE
I am currently developing a function that calculates the average price and total value based on the requested quantity. For instance:
async calculateValues (first_100) {
let market_data = await auctions_db.aggregate([
{
$match: {
item: 9999,
}
},
{
$sort: {
price: 1
}
},
//OUTCOME
]);
}
//OUTCOME
At this stage, I have the following documents:
{
item_id: 9999,
price: 1..Number
quantity: 1..200
value: price x quantity //not a virtual field
},{
another document...
}
My objective is to sum the prices until the quantity reaches or exceeds 100. In other words:
I do not want to sum the first 100 documents sorted by price ascending (in which case I would use .limit)
Currently, I am using collection.find({condition}).cursor() with the same condition and iterating through each document in a separate for loop. However, I have heard MongoDB can achieve the same result using an aggregate stage with a $cond block.
I believe that after the //Result stage, the next $operator should be a $group stage, like this:
{
$group: {
_id: "$lastModified",
quantity: {$sum: {$cond: if/else }" $quantity"},
if (below 100) {$sum: "$value" }
}
}
Yet, I am unsure how to implement this. Can someone provide me with an example? Or is there no substantial difference between using an aggregate stage and .find({}).cursor along with manual iteration?