查询和总和全部与猫鼬

问题描述:

我想获取所有用户 user_totaldocs user_totalthings ,并希望总和变量。

I want to fetch all users user_totaldocs and user_totalthings and want to sum those variables.

怎么可能?这是用户架构:

How can it's possible? Here is user schema:

var user_schema = mongoose.Schema({
    local : {
        ...
        ...
        user_id          : String,
        user_totaldocs   : Number,
        user_totalthings     : Number
        ....

    }
});


您可以使用聚合管道将计算字段添加到结果中。下面有一些例子,使用 mongo shell,但是在Mongoose的 Aggregate()helper 是相似的。

You can use the Aggregation Pipeline to add calculated fields to a result. There are some examples below using the mongo shell, but the syntax in Mongoose's Aggregate() helper is similar.

例如,要计算总和(每个用户文档),您可以使用 $ add 表达式 $ project stage

For example, to calculate sums (per user document) you can use the $add expression in a $project stage:

db.user.aggregate(
    // Limit to relevant documents and potentially take advantage of an index
    { $match: {
        user_id: "foo"
    }},

    { $project: {
        user_id: 1,
        total: { $add: ["$user_totaldocs", "$user_totalthings"] }
    }}
)

要计算多个文档的总计数,您需要使用 $ group stage 使用 $ sum 累加器,例如:

To calculate totals across multiple documents you need to use a $group stage with a $sum accumulator, for example:

db.user.aggregate(
    { $group: {
        _id: null,
        total:       { $sum: { $add: ["$user_totaldocs", "$user_totalthings"] } },
        totaldocs:   { $sum: "$user_totaldocs" },
        totalthings: { $sum: "$user_totalthings" }
    }}
)

您可能只需要一个总计字段;我已经在 totaldocs totalthings 中添加了计算多个字段的示例。

You may want only the one total field; I've added in totaldocs and totalthings as examples of calculating multiple fields.

_id null 将组合所有传递给 $ group stage,但您也可以在此使用其他条件(例如按 user_id 分组)。

A group _id of null will combine values from all documents passed to the $group stage, but you can also use other criteria here (such as grouping by user_id).