Taking sum of “column” in MongoDB

后端 未结 7 534

In MySQL, I would simply go \"SELECT sum(pts) FROM table\" to get the sum of the pts column on the table. However, I am converting this application to MongoDB and cannot fin

7条回答
  •  误落风尘
    2020-12-10 19:35

    Another solution is to create a script in the database, that will sum the require data and return your result something like:

    The Script

    function sum() {
       var sum = 0;
       for (var query = db.collection.find({}, {type: 1, _id:0}); query.hasNext();) {
          sum += query.next();
       }
       return sum;
    }
    

    PHP

    In php after setting the connection with the db, it will be something like:

    $toexec = 'function(x, y) { return sum() }';
    $response = $database->execute($toexec, array());
    

    Look this tutorial to learn more about scripting in mongo with php.

    http://pointbeing.net/weblog/2010/08/getting-started-with-stored-procedures-in-mongodb.html

提交回复
热议问题