Clip Clip - 3 months ago 13
Node.js Question

Omit certain results in a subdocument MongoDB

I am querying a list of items and only returning the items with contain a given ID in the

provider_cost_dict
. For instance, if I pass
providerId = 10001
, then only items with an entry in
provider_cost_dict
that match the provider ID will return.

How can I modify my code so that I can omit all the provider_cost_dict's that do not match the provider ID?

Here is my current code:

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));

});


Here is what my response looks like:

{
"_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


If I passed `10001 how could I make my return look like:

{
"_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
}
}

Answer

You can specify a projection to the query so that only your desired cost dict is shown like so

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( ...
Comments