【问题标题】:Get length of array within array mongodb获取数组mongodb中的数组长度
【发布时间】:2017-06-23 20:49:41
【问题描述】:

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

[
  {
    "_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]
});

【问题讨论】:

  • 请不要发布图片编辑您的问题以添加文档

标签: mongodb mongoose aggregation-framework


【解决方案1】:

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

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

这里是猫鼬

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

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2015-08-14
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多