MongoDb sum query

后端 未结 2 2035
你的背包
你的背包 2020-12-13 03:34

For example I have the following data in MongoDB:

{ \"_id\" : ObjectId(\"524091f99c49c4c3f66b0e46\"), \"hour\" : 10, \"incoming\", 100}
{ \"_id\" : ObjectId(         


        
相关标签:
2条回答
  • 2020-12-13 04:04

    As llovet suggested, the aggregation framework is the way to go. Here's what your query would look like:

    db.CollectionNameGoesHere.aggregate({ $match: {
        $and: [
            { hour: { $gte: 11 } },
            { hour: { $lte: 12 } }
        ]
    } },
    { $group: { _id : null, sum : { $sum: "$incoming" } } });
    

    You can also shape the resulting document to only contain the sum by adding a $project operator at the end of the pipeline, like so:

    { $project: { _id: 0, sum: 1 } }
    
    0 讨论(0)
  • 2020-12-13 04:05

    Some examples if you use mongoose:

    1. Calculate total sum of product prices :
    Products.aggregate([ { $match: {} }, { $group:
      { _id : null, sum : { $sum: "$Price" } }
    }])
    .then(res => console.log(res[0].sum));
    

    ( { $match: {} }, can be removed. )


    1. Sum of Product's prices in each category:
    Products.aggregate([{ $group:
      { _id : '$Category', sum : { $sum: "$Price" } }
    }])
    .then(res => console.log(res));
    
    0 讨论(0)
提交回复
热议问题