存储文件中的总价格或通过汇总解决?

时间:2014-03-18 09:30:37

标签: mongodb aggregation-framework

我有一个耗材集合,其中包含以下设计的文档:

{
    _id: ObjectId("532807bdf09ae6e7464191c1"),
    supplier: {
        $ref: "suppliers",
        $id: ObjectId("5328078cf09ae6e7464191c0")
    },
    state: {
        created: ISODate("2013-12-10T00:00:00Z"),
        shipped: ISODate("2013-12-11T00:00:00Z"),
        cleared: ISODate("2013-12-11T00:00:00Z")
    },
    materials: [
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191b9")
            },
            quantity: 1,
            price: 4.8
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191ba")
            },
            quantity: 1,
            price: 3.5
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191bb")
            },
            quantity: 1,
            price: 4.1
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191bc")
            },
            quantity: 1,
            price: 4.3
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191bd")
            },
            quantity: 1,
            price: 3.6
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191be")
            },
            quantity: 1,
            price: 3.15
        },
        {
            material: {
                $ref: "materials",
                $id: ObjectId("53280782f09ae6e7464191bf")
            },
            quantity: 1,
            price: 5
        }
    ]
}

在商业逻辑中,我现在有时想知道单个耗材文件的总价格。

这可以通过聚合

来实现
db.supplies.aggregate({
  $unwind: "$materials" // go through material array
},
{
  $project: {
    "total": {
      // calculate price of each item (1.19 is vat)
      $multiply: ["$materials.quantity", "$materials.price", 1.19]
    }
  }
},
{
  $group: {
    "_id": "$_id",
    "total": {
      // sum all items together
      $sum: "$total"
    }
  }
});

然而,这样做是否聪明,或者我应该添加一个"总计"字段到文件?

0 个答案:

没有答案