Wednesday, 5 April 2017

Aggregate method not working as expected

Following is my Collection Called Run

var Run = [{
        ID: 1,
        Name: 'TestRun',
        Comments: 'TestRun',
        Status: [{
            Cur: 'Active',
            Mapper: {
                Area: 'BH',
                State: 'MH'
            }
        },
        {
            Cur: 'Inactive',
            Mapper: {
                Area: 'BO',
                State: 'DU'
            }
        }]
    }]

I would like to create a query when I get all the data with 'Area' as 'BH' so that I get the result as follows

    Status: [{
        Cur: 'Active',
        Mapper: {
             Area: 'BH',
             State: 'MH'
        }
   }]

When I fire this query in mongodb prompt:

db.Run.aggregate([ 
    {$match: {'Status.Mapper.Area': 'BO'}},
        {$project: { 
            Status: 
                {$filter: { 
                    input: '$Status', 
                    as: 'script', 
                    cond: {$eq: ['$$script.Mapper.Area','BO']}
            }},
        _id: 0
    }} 
]).pretty();

The result is as expected. However when I try to run this query using Nodejs it returns no result.

db.collection('Run').aggregate([
                    {$match: {'Status.Mapper.Area': 'BO'}},
                    {$project: {
                        Status: {$filter: {
                            input: '$Status',
                            as: 'script',
                            cond: {$eq: ['$$script.Mapper.Area', 'BO']}
                        }},
                        _id: 0
                    }}
                ]).toArray(function(error, docs) {
                    console.log('found docs:2 ');
                docs.forEach(function(doc) {
                    console.log('found docs:3 ');
                    console.log(JSON.stringify(doc));
                }); 
            }); 

The query is almost same as the one I used in MongoDB prompt. Since no errors are thrown it seems there is something wrong with the filter clause. Appreciate your help with this.



via user2147744

No comments:

Post a Comment