【问题标题】:How to aggregate array of document in MongoDB如何在 MongoDB 中聚合文档数组
【发布时间】:2020-02-08 05:23:24
【问题描述】:

我有以下架构:

var orderSchema = new mongoose.Schema({
    deleted: Boolean,
    clientName: String,
    clientPhone: String,
    products: [{
        name: String,
        quantity: Number,
        price: Number
    }],
    observations: String,
    date: {
        type: Date,
        default: Date.now
    },
    seller: String,
    orderNumber: Number,
    total: Number
});

我想进行一个汇总查询,对每个产品求和并将quantity*price 添加到total,然后将总数返回给我。但是,如果我有多个产品,每个产品都作为一个文档,然后总结所有文档而不是这个,我只知道该怎么做。

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用$reduce 做到这一点:

    db.collection.aggregate([{
        $addFields: {
            "total": {
                $reduce: {
                    input: "$products",
                    initialValue: '$total',
                    in: { $add: [{ $multiply: ["$$this.quantity", "$$this.price"] }, '$$value'] }
                }
            }
        }
    }])
    

    测试: MongoDB-Playground

    【讨论】:

    • 什么是总数??
    • @GuerlandoOCs:我没听懂? total = total + sum of quantity*price of all products..
    • 您在文档中添加了一个“总计”字段。如果我只想返回包含总计字段的新文档怎么办?而不是 addFields 我返回一个新文档
    • @GuerlandoOCs :您可以尝试使用$project 而不是$addFields,也可以在项目中添加_id:0 以排除它。一般$addFields 将用新的Total 替换现有字段值,或者如果它不存在,它将在列中添加一个新字段..
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多