javascript - MongoDB Mongoose 聚合/数学运算

标签 javascript json node.js mongodb mongoose

我在理解 $aggregation 方法在 Mongoose 中的工作方式时遇到问题。老实说,我在 mongoose 文档中找不到任何代码示例(我在他们的网站上什至没有找到 [search] 选项 [google site:mongoosejs.com helps me])

所以,我希望有人能帮我解释一下并回答我的问题。

例如,我的集合中有各种文档,字段为:

    { "_id": 1, "item":47139, "total_price": 560000, "quantity": 56, "lastModified" : 1491748073000 }
    { "_id": 3, "item":47140, "total_price": 1750000, "quantity": 150, "lastModified" : 1491748073000 }

并且我想$sum 具有id: 47139timestamp: 1491748073000 的文档的所有“数量”。至于现在这段代码工作正常并为我提供了必要的数据:

    var server = mongoose.model('Name_of_my_Schema', Schema);

    server.find({ lastModified : 1491748073000, item : 47139 }, null, {sort: 'buyout'},function (err, res) {
        total = 0;
        for (i = 0; i < res.length; i++) {  //sorry, map.reduce, but not this time
            total += res[i].quantity; 
        }
        console.log(total); //in this case total = 256
    });

但是否可以通过 mongoose 执行此操作?根据 mongo 文档,我应该使用此代码来匹配必要的文档数组,如下所示:

  server.aggregate().match({
   lastModified : 1491748073000,
    item : 47139
  }).exec(function (err, result){
    console.log(result);
     console.log(err);
  });

然后使用$group 将必要的数据和{ $sum: "quantity"} 分组,但是接下来我应该做什么?如果我只想收到所有数量的总和,为什么要使用 $group?

有人可以告诉我我错过了什么吗?

最佳答案

正如您所说的那样,您错过了 $group 管道步骤进行总和聚合。按照以下方式完成管道:

server.aggregate()
    .match({
        "lastModified": 1491748073000,
        "item": 47139
    })
    .group({
        "_id": null,
        "total": { "$sum": "$quantity" }
    })
    .exec(function (err, result){
        console.log(result);
        console.log(err);
    });

或作为运算符数组:

server.aggregate([
    { "$match": { "lastModified": 1491748073000, "item": 47139 } },
    { "$group": { "_id": null, "total": { "$sum": "$quantity" } } } 
]).exec(function (err, result){
    console.log(result);
    console.log(err);
});

关于javascript - MongoDB Mongoose 聚合/数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450940/

相关文章:

javascript - 如何使用索引从数组中删除值(特定于 Ant Design)?

javascript - 导航栏/菜单在较小的屏幕上消失 - CSS 问题

javascript - 如何通过键获取 Javascript 对象的所有值?

JAVA : How make custom inner class for complex Json

python - Python 中是否有等效的 NODE_ENV

javascript - 错误 : An API error occurred: invalid_auth

c# - 用于验证 C# 和 Javascript 中的 FQDN 的正则表达式

javascript - Json 对象在 while 循环中断页面期间进行字符串检查

javascript - 解析 JSON 文件以生成并返回另一个包含所需数据的 JSON

node.js - 在mongoosastic中搜索没有任何结果