获取数组mongodb中的数组长度

时间:2015-11-21 16:02:21

标签: mongodb mongoose aggregation-framework

我正在尝试计算以下架构的每个问题的投票数。

[
  {
    "_id": "564b9e13583087872176dbd2",
    "question": "fav NFL team",
    "choices": [
      {
        "text": "St. Louis Rams",
        "_id": "564b9e13583087872176dbd7",
        "votes": [
          {
            "ip": "::ffff:192.168.15.130",
            "_id": "564b9e30583087872176dbd8"
          },
          {
            "ip": "::ffff:192.168.1.1",
            "_id": "564bb355e4e1b7200da92668"
          }
        ]
      },
      {
        "text": "Oakland Raiders",
        "_id": "564b9e13583087872176dbd6",
        "votes": [
          {
            "ip": "::ffff:192.168.1.135",
            "_id": "564bb273e4e1b7200da92667"
          }
        ]
      },
      {
        "text": "Denver Broncos",
        "_id": "564b9e13583087872176dbd5",
        "votes": []
      },
      {
        "text": "Kansas City Chiefs",
        "_id": "564b9e13583087872176dbd4",
        "votes": [
          {
            "ip": "::ffff:192.168.1.100",
            "_id": "564bab48e4e1b7200da92666"
          }
        ]
      },
      {
        "text": "Detroit Lions",
        "_id": "564b9e13583087872176dbd3",
        "votes": [
          {
            "ip": "::ffff:192.168.15.1",
            "_id": "564b9f41583087872176dbd9"
          }
        ]
      }
    ]
  }
]

我假设我将不得不使用聚合和总和。 我能够得到选择数组的计数,但我不确定如何更深入。

db.polls.aggregate([{$unwind: '$choices'}, {$group:{_id:'$_id', 'sum':{$sum:1}}}])

“赞成NFL球队”的投票数为5。

另外,这里引用的是我生成模式的猫鼬代码

var mongoose = require('mongoose');
var voteSchema = new mongoose.Schema({
    ip: 'String'
});
var choiceSchema = new mongoose.Schema({
    text: String,
    votes: [voteSchema]
});
exports.PollSchema = new mongoose.Schema({
    question: {
        type: String, 
        required: true
    },
    choices: [choiceSchema]
});

1 个答案:

答案 0 :(得分:0)

我想出了如何在芒果中做到这一点,我需要另一个放松。

db.polls.aggregate([
    {$unwind: '$choices'},
    {$unwind:'$choices.votes'},
    {$group:{
        _id:'$_id', 
        'sum':{
            $sum:1
        }
    }}
])

这里是mongoose

Poll.aggregate([
    {$unwind: '$choices'},
    {$unwind: '$choices.votes'},
    {$group:{
        _id: '$_id',
        'sum': {
            $sum:1
        }
    }}
], function(err, result) {
    if (err) {
        console.log(err);
    }
    res.json(result);
});