计算mongodb聚合上元素的百分比

时间:2018-03-16 07:20:25

标签: javascript mongodb mongoose aggregation

我有一个像这样的Mongoose数据集:

{
    "_id" : ObjectId("5aa78cd3d2dcd60dc00f7c42"),
    "uid" : "5aa1205d52725521e48f4e93",
    "net" : 301,
    "total" : 400,
    "score_percentage" : 0,
    "lastmodified" : ISODate("2018-03-13T09:17:31.521Z"),
    "__v" : 0
}

现在我想从总价值中计算净值的百分比。

期望的结果将是这样的:

{
    "_id" : ObjectId("5aa78cd3d2dcd60dc00f7c42"),
    "uid" : "5aa1205d52725521e48f4e93",
    "net" : 340,
    "total" : 400,
    "score_percentage" : 40,
    "lastmodified" : ISODate("2018-03-13T09:17:31.521Z"),
    "__v" : 0
}

为此,我将聚合mongodb Query但不获取结果。我实施的是:

db.collection.aggregate([
                {$match: { "uid": "5aa1205d52725521e48f4e93"}},
                {
                    $addFields: {
                                            score_percentage: { $divide: [ { $multiply: ["$net", 100]}, "$total" ]}
                    }
                },
                {
                    $out: "collectionname"
                }
            ], function(error, data){
                console.log(data);

//It will return 85% i.e 340*100/400;
//But I want to treat this as 100 like: 340 will be 40 and 400 will be 100.
//So desired result will be like 40%
});

非常感谢任何帮助。

0 个答案:

没有答案