How to do a sql query in MoongoDb with php?

0

How do I query the following sql query in Mongo?

select * from myDB WHERE nm_pesquisa LIKE "%SAO%" AND tp_m = "A" OR tp_m = "H";

I tried the following but unsuccessfully:

$query = [
    'nm_pesquisa' => ['$regex' => MDB::Regex($nm)],
    'tp_m' => "A",
    '$or' => [['tp_m' => "A"]]
];
    
asked by anonymous 27.04.2018 / 22:10

1 answer

0

First (even though it is not your current problem) your query is "wrong":

select * from myDB WHERE nm_pesquisa LIKE "%SAO%" AND tp_m = "A" OR tp_m = "H";

You have a OR next to a AND , in mysql it might even work, but it sure seems to me wrong or maybe it will bring some unexpected result or something missing, anyway I think that would be really the expected:

select * from myDB WHERE nm_pesquisa LIKE "%SAO%" AND (tp_m = "A" OR tp_m = "H");

A detail FROM does not select the bank, you may know, it selects the table, of course you can select a table in a specific bank, but still the table is, just to explain, is that myDB there may not make sense, anyway I assume it's a typo.

Now we go to OR and AND in MongoDB, basically we would have to use $or to solve and apply both conditions of OR of SELECT inside it, your query probably looks like this:

  

Note: I kept myDB , but this is the document

     

Note: I used /.*SAO.*/ which is regex

db.myDB.find({
   "nm_pesquisa": { $regex: /.*SAO.*/ },
   $or: [
      {"tp_m": "A"}, {"tp_m": "H"}
   ]
})

With the native PHP libs: link , I think it should look like this:

 $regex = new MongoDB\BSON\Regex('.*SAO.*');

If it is case-insensitive it would look like this:

$regex = new MongoDB\BSON\Regex('.*SAO.*', 'i');

So then just pass $regex on the filter and conditions from OR to tp_m are in $or => [...]

$filter = [
    'nm_pesquisa' => $regex,
    '$or' => [
         [ 'tp_m' => 'A' ], [ 'tp_m' => 'H' ]
    ]
];
  

If I have something wrong let me know, I have never worked with mongoDB, what I answered above was based on the documentation, so I may have understood something wrong

    
28.04.2018 / 03:40