多个mongoose count()查询到MongoDB [英] Multiple mongoose count() queries to a MongoDB

查看:435
本文介绍了多个mongoose count()查询到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先:我 - > MongoNoob我知道这已经有过一种或另一种方式的问题,但直到现在我还没有找到任何具体内容。
假设我有两个这样描述的Moongoose模型:

first: me -> MongoNoob and I know this has already been asked in one or the other way, but I haven't found anything specific until now. Let's say I have two Moongoose Models described like this:

var pollSchema = mongoose.Schema({
    title: String,
    choices: [{
        content: String
    }]
});
var choiceSchema = mongoose.Schema({
    poll_id: mongoose.Schema.ObjectId,
    option: Number
});

UI显示轮询,当用户选择一个选项时,它会被写入 choiceSchema 模型。现在我想创建一个'统计',告诉我有多少用户选择了选项1,选项2,选项3,....
我可以简单地用获取民意调查的所有选项找到并在服务器代码中生成统计信息,但如果我有一百万用户选择,我将不得不处理相同大小的数组。这不可能是对的。
但是我可以生成一个查询并使用 count()方法:

A UI shows the poll and when a user selects a choice, it is written into the choiceSchemamodel. Now I would like to create a 'statistic', telling me how many users selected option 1, option 2, option 3,.... I could simply fetch all choices for a poll with find and generate the statistic in server code, but if I had a million user choices, I would have to deal with an array of the same size. This cannot be right. I could however generate a query and use the count()method:

var query = Choice.find({poll_id: someId}),
query.where('option', 1);
var resultForOption1;
query.count(function(err, count)) {
    resultForOption1 = count;
});

我如何为多个选项执行此操作并将结果加入(哈哈)到数组中?由于这都是异步的,我会嵌套调用,但这不是一个可变数量的查询的选项。

How would I do this for multiple options and 'join' (haha) the results into an array? Since this is all asynchronous I would have nest the calls, but that is not an option for a variable number of queries.

我是否想念树木: - )?有人可以指出我正确的方向吗?

Do I miss the wood for the trees :-)? Can somebody point me in the right direction?

BR,
Daniel

BR, Daniel

推荐答案

您可以使用 aggregate 来执行此操作:

You can use aggregate to do this:

Choice.aggregate(
    {$group: {_id: {poll_id: '$poll_id', option: '$option'}, count: {$sum: 1}}}
).exec(...);

这将对选项集合文档进行分组 poll_id 选项并计算每个的出现次数,给出如下输出:

This will group the choices collection docs by poll_id and option and count the occurrences of each, giving output that looks like:

{
  "result": [
    {
      "_id": {
        "poll_id": 2,
        "option": 3
      },
      "count": 1
    },
    {
      "_id": {
        "poll_id": 1,
        "option": 2
      },
      "count": 2
    },
    {
      "_id": {
        "poll_id": 2,
        "option": 2
      },
      "count": 1
    },
    {
      "_id": {
        "poll_id": 1,
        "option": 1
      },
      "count": 1
    }
  ],
  "ok": 1
}

然后您可以使用后续 $ group $ project 您的汇总管道中的阶段,以进一步分组和重塑基因根据需要评估文档。

You can then use subsequent $group and $project stages in your aggregate pipeline to further group and reshape the generated docs as needed.

这篇关于多个mongoose count()查询到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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