用mongoose查询和总结

Laz*_*azy 9 mongoose mongodb node.js express

我想获取所有用户user_totaldocs,user_totalthings并希望对这些变量求和.

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

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

    }
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*nie 17

您可以使用聚合管道将计算字段添加到结果中.下面有一些使用mongoshell的例子,但是Mongoose的Aggregate()帮助器中的语法是类似的.

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

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"] }
    }}
)
Run Code Online (Sandbox Code Playgroud)

要计算多个文档的总计,您需要使用具有累加器$group阶段,例如:$sum

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

你可能只想要一个total领域; 我一直在增加totaldocs,并totalthings作为计算多个字段的例子.

A组_idnull将传递给所有文档合并值$group阶段,但你也可以在这里使用其他标准(如通过分组user_id).


Dan*_*ish 6

您可以使用mongodb提供的聚合框架。对于您的情况-

如果您要在整个集合中获取user_totaldocs的总和和user_totalthings的总和(对所有用户而言),请执行-

db.user_schemas.aggregate(
 [
  {
    $group : {
       user_id : null,
       user_totaldocs: { $sum: "$user_totaldocs"}, // for your case use local.user_totaldocs
       user_totalthings: { $sum: "$user_totalthings" }, // for your case use local.user_totalthings
       count: { $sum: 1 } // for no. of documents count
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

要对集合中特定用户的user_totaldocs和user_totalthings求和(假设一个用户有多个文档),这将返回每个用户的总和,DO-

db.user_schemas.aggregate(
 [
  {
    $group : {
       user_id : "$user_id", 
       user_totaldocs: { $sum: "$user_totaldocs"}, // for your case use local.user_totaldocs
       user_totalthings: { $sum: "$user_totalthings" }, // for your case use local.user_totalthings
       count: { $sum: 1 } // for no. of documents count
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

无需提供个人用户ID。

有关更多信息,请阅读:1. http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group 2. http://docs.mongodb.org/manual/core/aggregation/