Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elemMatch query does not work in php

This mongodb query works correctly returning documents with matching sub-document criteria

db.user.find(
    {Type: {"$in": ["local","google"]}, 
     Alerts:{$elemMatch:{"Frequency.Type":"daily","IsActive":true}}
})

When I convert this into a php array it returns nothing

$qry = array("Type"=>array('$in'=>array("local","google")),
       array('Alerts'=>array('$elemMatch'=>array('Frequency.Type'=>'daily','IsActive'=>true))));

This is structure of document

{
    "Email" : "[email protected]",
    "Type" : "confirmed",
    "FName" : "Sung",

    "Alerts" : [ 
        {
            "Keyword" : "administrative",
            "Frequency" : {
                "Type" : "weekly"
            }
            "IsActive" : true
        },
        {
            "Keyword" : "marketing",
            "Frequency" : {
                "Type" : "daily"
            }
            "IsActive" : true
        }
    ]
}

When I take the elemMatch portion out of the php array it returns rows. So I am connecting and there is data there. Not sure if I coded the array right but I think $elemMatch not supported correctly in php mongodb library. Aggregation is not an option. I need a cursor since this will return large dataset and dont want to crash the server. Searched the web and cannot find a working example of $elemMatch mongodb query done in php.

like image 660
Andy N Avatar asked Sep 13 '25 01:09

Andy N


1 Answers

You had one too many arrays.

$qry = array(
    "Type"=>array('$in'=>array("local","google")),
    "Alerts"=>array('$elemMatch'=>array(
        "Frequency.Type"=> "daily",'IsActive'=>true
    ))
);

In the future, try to indent your code as I have done so you can clearly see the structure. Also since you are comparing to a known JSON structure, do this:

echo json_encode( $qry, JSON_PRETTY_PRINT ) ."\n";

And then you can clearly see what you have done that does not match the expected output.

like image 72
Neil Lunn Avatar answered Sep 14 '25 13:09

Neil Lunn