4

我找不到任何这样的例子,所以我不确定这是否可能。我有以下文件

db.mytest.insert([
    { date: new Date('2013-06-01'), 
      account: 'A', 
      ids: [ { id: '1vb', sale: 50 }, { id: 'xy2', sales: 25 } ]
    }, 
    { date: new Date('2013-06-02'), 
      account: 'A', 
      ids: [ { id: '1vb', sales: 10 }, { id: 'xy2', sales: 5 } ]
    } 
])

我试图得到以下结果

[{ account: 'A': 
   ids: [ { id: '1vb', salesAmount: 60, salesCount: 8 }, 
          { id: 'xy2', salesAmount: 30, salesCount: 3 } 
         ]
}]

我已经尝试过以下管道

var unwind = { $unwind: '$ids' };
var group = { $group: { 
    _id: { id: '$ids.id' }, 
    ids: { $addToSet: 
            { 
              salesAmount: { $sum: '$ids.salesAmount' }, 
              salesCount: { $sum: '$ids.salesCount' }
            }
         }
 }};

db.mytest.aggregate([unwind, group])

但它返回此错误

Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:7)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:1)
at (shell):1:11
Sun Jul  7 18:53:26.177 JavaScript execution failed: aggregate failed: {
    "errmsg" : "exception: invalid operator '$sum'",
    "code" : 15999,
    "ok" : 0
} at src/mongo/shell/collection.js:L898
4

1 回答 1

6

我让它与这个管道一起工作。

var unwind = { "$unwind" : "$ids" };
var group = {
"$group" : {
    "_id" : {
        "account" : "$account",
        "id" : "$ids.id"
    },
    "idSalesAmount" : {
        "$sum" : "$ids.salesAmount"
    },
    "idSalesCount" : {
        "$sum" : "$ids.salesCount"
    }
}};
var group2 = {
"$group" : {
    "_id" : "$_id.account",
    "ids" : {
        "$addToSet" : {
            "id" : "$_id.id",
            "salesAmount" : "$idSalesAmount",
            "saleCount" : "$idSalesCount"
        }
    }
}};
var project = { "$project" : { "account" : "$_id", "ids" : 1, "_id" : 0 } };

db.mytest.aggregate([unwind, group, group2, project])
于 2013-07-08T15:30:46.877 回答