Guruprasad Rao Guruprasad Rao - 5 months ago 40
Node.js Question

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}}]
}
]
}


}

Answer

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

Comments