Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple $and with multiple $or in $match mongoose

Expected condition

if(pid==req.session.pid && 
   ((status==0 && StatusDate1>=somedate)||(status==1 && StatusDate2>=somedate)||
    (status==2 && StatusDate3>=somedate)||(status==0 && StatusDate1>=somedate)))

I have tried writing below $match statement to meet the above condition, but for some reason it is not as expected.

var match =  { $match: { 
    $and: [ 
        { practiceId: req.session.p_id },  
        {
            $or:[{status : 0, StatusDate1:{$gte:somedate}}] 
        }, 
        {           
            $or:[{status : 1, StatusDate2:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 2, StatusDate3:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 3, StatusDate4:{$gte:somedate}}] 
        }]
    }
}

Could anyone please point me in the right direction?

Update

Tried below versions, still did not get what I was expecting.

Attempt 1

var match =  { $match: { 
    $and: [ 
        { practiceId: req.session.p_id }],
    $and:[  
        {
            $or:[{status : 0, StatusDate1:{$gte:somedate}}] 
        }, 
        {           
            $or:[{status : 1, StatusDate2:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 2, StatusDate3:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 3, StatusDate4:{$gte:somedate}}] 
        }]
    }
}

Attempt 2

var match =  { $match: { 
    practiceId: req.session.p_id ,
    $and:[  
        {
            $or:[{status : 0, StatusDate1:{$gte:somedate}}] 
        }, 
        {           
            $or:[{status : 1, StatusDate2:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 2, StatusDate3:{$gte:somedate}}] 
        },
        {           
            $or:[{status : 3, StatusDate4:{$gte:somedate}}] 
        }]
    }
}

Attempt 3

var match =  { $match: { 
    practiceId: req.session.p_id,
        $and:[  
        {
            $or:[{status : 0,StatusDate1:{$gte:somedate}}], 
            $or:[{status : 1,StatusDate2:{$gte:somedate}}], 
            $or:[{status : 2,StatusDate3:{$gte:somedate}}], 
            $or:[{status : 3,StatusDate4:{$gte:somedate}}] 
        }
    ]
  }

}

like image 363
Guruprasad J Rao Avatar asked Jun 09 '16 10:06

Guruprasad J Rao


1 Answers

Syntax :- { $or: [ expression1, expression2, ... ] }

See if this could help you:-

var match =  { $match: { 
$and: [ 
    { practiceId: req.session.p_id },  
    {
        $or:[{status : 0, StatusDate1:{$gte:somedate}},
             {status : 1, StatusDate2:{$gte:somedate}},
             {status : 2, StatusDate3:{$gte:somedate}},
             {status : 3, StatusDate4:{$gte:somedate}}] 
    }]
}
}

Added , separated condition inside $or . See $or

like image 53
Shrabanee Avatar answered Nov 15 '22 06:11

Shrabanee