簡體   English   中英

MongoDB Mongoose 聚合/數學運算

[英]MongoDB Mongoose aggregation / math operations

我在理解 Mongoose 中的$aggregation方法如何工作時遇到問題。 老實說,我在 mongoose 文檔中找不到任何代碼示例(我什至沒有在他們的網站上找到 [search] 選項 [google site:mongoosejs.com 幫助我])

所以,我希望有人能幫助我解釋這一點並回答我的問題。

例如,我的集合中有各種文檔,其中包含以下字段:

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

我想對id: 47139timestamp: 1491748073000文檔的所有“數量”進行$sum 至於現在這段代碼工作正常,並為我提供了必要的數據:

    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
    });

但是可以通過貓鼬來做這個操作嗎? 根據 mongo docs,我應該使用此代碼來匹配必要的文檔數組,如下所示:

  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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM