在子文档MongoDB中省略某些结果

时间:2016-08-31 04:24:27

标签: javascript node.js mongodb mongodb-query

我正在查询项目列表,只返回provider_cost_dict中包含给定ID的项目。例如,如果我传递providerId = 10001,则只有provider_cost_dict中与提供者ID匹配的条目的项目才会返回。

如何修改我的代码,以便省略与提供商ID不匹配的所有provider_cost_dict?

这是我目前的代码:

var procedures = db.collection('procedures');

var query = {};
query['provider_cost_dict.' + req.query.providerId] = {$exists: true };

procedures.find({}).toArray(function(err, result) {
    // Send the result back via JSON.
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(result, null, 3));

});

以下是我的回复:

{
          "_id": "57c62cb53673aaf5f6beacf9",
          "natl_total_cost": 1274787840,
          "natl_average": 8338.487,
          "natl_report_count": 152880,
          "name": "COPD (WITH MAJOR COMPLICATIONS)",
          "provider_cost_dict": {
             "10001": {
                "report_count": 144,
                "total_cost": 957334,
                "average_cost": 6648.153
             },
             "10005": {
                "report_count": 200,
                "total_cost": 1321644,
                "average_cost": 6608.22
             },
             "10006": {
                "report_count": 214,
                "total_cost": 1345658,
                "average_cost": 6288.1216

如果我通过了`10001,我怎么能让我的回报看起来像:

{
          "_id": "57c62cb53673aaf5f6beacf9",
          "natl_total_cost": 1274787840,
          "natl_average": 8338.487,
          "natl_report_count": 152880,
          "name": "COPD (WITH MAJOR COMPLICATIONS)",
          "provider_cost_dict": {
             "10001": {
                "report_count": 144,
                "total_cost": 957334,
                "average_cost": 6648.153
             }
}

1 个答案:

答案 0 :(得分:2)

您可以为查询指定projection,以便只显示所需的费用字典

var query = { 'provider_cost_dict.10001': { $exists: true } };
var project = { 
    'natl_total_cost': 1,
    'natl_average': 1,
    'natl_report_count': 1,
    'name': 1,        
    'provider_cost_dict.10001': 1 
};
procedures.find(query, project).toArray( ...