查询和总和全部与猫鼬 [英] Query and sum all with mongoose

查看:120
本文介绍了查询和总和全部与猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取所有用户 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"] }
    }}
)

要计算多个文档的总计数,您需要使用<啊ref =http://docs.mongodb.org/manual/reference/operator/aggregation/group/ =noreferrer> $ 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 将组合所有传递给<$ c $的文档的值c> $ 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).

这篇关于查询和总和全部与猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆