0

有没有办法获得每个运动类别支付的金额?它不能仅限于“John”,而是在所有集合文档中。

所提供数据的预期查询返回:

{
  {"Fight":   [100,95] },
  {"Running": [50]     }
}

数据示例:

{"_id":"5z621578b0ce483b9866fb1f",
 "Name":"John",
 "Sports":[
           {"Category":"Fight",
            "Billing":[
                       {"Month":"Jan",
                        "Status":"Paid",
                        "Price":100},
                      {"Month":"Feb",
                       "Status":"Not Paid",
                       "Price":125}, 
                      {"Month":"Mar",
                       "Status":"Paid",
                       "Price":95}      
                      ]
           },

          {"Category":"Running",
           "Billing":[
                      {"Month":"Jan",
                       "Status":"Not Paid",
                       "Price":200}, 
                      {"Month":"Feb",
                       "Status":"Paid",
                       "Price":50}  
                     ]
          }
      ]
}

换句话说:我需要比较每个嵌套对象中的计费状态并检查它是否为“已支付”,如果为真,则将 相应的计费对象价格添加到相应的运动类别数组中。

对于集合中的所有文档,具有多个运动类别和多个计费月份。但总是相同的嵌套结构。

先感谢您!

4

1 回答 1

0

正如威利斯在他的评论中所说,你会想要使用聚合:https ://docs.mongodb.com/manual/aggregation/


以下聚合将为您提供您正在寻找的数据(将 billings 替换为您的集合的实际名称):

db.billings.aggregate([
    { $unwind: '$Sports'},
    { $unwind: '$Sports.Billing'},
    { $match: { 'Sports.Billing.Status': 'Paid' } },
    {
        $group: {
            _id: '$Sports.Category',
            Category: {$first: '$Sports.Category'},
            Prices: { $push: '$Sports.Billing.Price' }
        }
    },
    { $project: {_id: 0} }
]);

此聚合的结果将如下所示:

[
    {
        "Category" : "Running",
        "Prices" : [ 
            50.0
        ]
    },
    {
        "Category" : "Fight",
        "Prices" : [ 
            100.0, 
            95.0
        ]
    }
]

您在问题中要求的确切格式有点不正常;在我看来,我认为最好将其保留在输出之上的聚合形式中。但是,如果您希望它的形式类似于您问题中的形式,那么聚合会更复杂一些:

db.billings.aggregate([
    { $unwind: '$Sports'},
    { $unwind: '$Sports.Billing'},
    { $match: { 'Sports.Billing.Status': 'Paid' } },
    {
        $group: {
            _id: '$Sports.Category',
            Prices: { $push: '$Sports.Billing.Price' }
        }
    },
    {
        $group: {
            _id: 0,
            Sports: { $push: { Category: '$_id', Prices: '$Prices' } }
        }
    },
    {
        $project: {
            Sports: {
                $arrayToObject: {
                    '$map': {
                        'input': '$Sports',
                        'as': 'el',
                        'in': {
                            'k': '$$el.Category',
                            'v': '$$el.Prices'
                        }
                    }
                }
            }
        }
    },
    { $replaceRoot: { newRoot: '$Sports'} }
]);
于 2019-02-16T15:50:36.960 回答