


I wrote a PHP version of MONGODB syntax parser, which can be queried through SQL-like syntax. I don't know if anyone needs it, so please share it.
转载请注明作者:wetouns
在使用MONGODB的时候写查询语句总是一件让人蛋疼的事情,如果查询复杂一点,要嵌套好多层对象,于是我就想,能不能使用类似SQL的语法来进行查询呢,这样子代码看起来更加易懂,书写也更为简单,于是就花了些时间把这个想法变为现实该解析器会将类似SQL的语法转换成MONGODB的查询对象,目前条件判断只支持and和or,以及>,<,>=,<=,=的查询,还支持括号表示判断的优先级哦,更多的暂时不支持,想扩展的可以自己改源码,简单说明一下语法和用法吧
例1,我要查询a=0的文档
$query = new MongoQueryParser(); $query->query("a=0"); $queryRst = $query->result;<br>最终$queryRst的结果将会如下图 <p><img src="/static/imghw/default1.png" data-src="http://image.codes51.com/Article/image/20150101/20150101160034_8499.png" class="lazy" alt=""><br></p> <p>例2:</p> <p>这回来个复杂点的</p> <pre code_snippet_id="569418" snippet_file_name="blog_20150101_2_7195815" name="code">$query = new MongoQueryParser(); $query->query("a=0 && b > 2"); $queryRst = $query->result;
例3:
再来个更复杂的
$query = new MongoQueryParser(); $query->query("(a=0 && b > 2) || c <= 5"); $queryRst = $query->result;
看完以上3个例子,相信不用说明用法,应该也会用了吧,嘿嘿,废话少说,贴上解析器的源码
<?php class MongoQueryParser { function __construct() { $this->result =[]; } public $result; public $leftFirstReg = "/\\(([^\\s]+)\\)(&&|\\|\\|)([^\\s]+$)/";//匹配左括号优先 public $rightFirstReg = "/([^\\s]+?)(&&|\\|\\|)\\(([^\\s]+)\\)$/";//右括号优先 public $allReg = "/\\(([^\\s]+)\\)(&&|\\|\\|)\\(([^\\s]+)\\)$/";//左右括号模式 public $reg1 = "/([^\\s]+)(&&|\\|\\|)([^\\s]+)/"; public $reg2 = "/([\\w]+)([=<>]+)([^\\s]+)/"; public $opMap = [">"=>'$gt',"<"=>'$lt',">="=>'$gte',"<="=>'$lte']; private $meetOr = false; /** * 将自定义的查询语句转换成MONGODB的查询语句 * 例1:a=3 * 例2:a>0&&a<2 * 例3:a>0&&a<2||c>3 */ function query($query){ $query =preg_replace("/\s/","",$query); $this->result = $this->exec($query,false,false); return $this->result; } function exec($query,$layer,$fromAnd){ if(preg_match($this->allReg, $query,$matches1) > 0 || preg_match($this->rightFirstReg, $query,$matches2) > 0 || preg_match($this->leftFirstReg, $query,$matches3) > 0 || preg_match($this->reg1, $query,$matches4)){ $mat = null; $leftSame = false; $rightSame = false; if(count($matches1) > 0){ $mat = $matches1; }else if(count($matches2) > 0){ $leftSame = true; $rightSame = false; $mat = $matches2; }else if(count($matches3) > 0){ $leftSame = false; $rightSame = true; $mat = $matches3; }else if(count($matches4) > 0){ $leftSame = true; $rightSame = true; $mat = $matches4; } $op = $mat[2]; $left = $mat[1]; $right = $mat[3]; if($op == "&&"){//如果操作符是AND $rst = null; if(!$layer || !$fromAnd){//如果不同层,或者调用来自上一层的or,那么就建立一个$and操作符 $rst['$and'] = []; $larr = $this->exec($mat[1],$leftSame,true); $rarr = $this->exec($mat[3],$rightSame,true); $rst['$and'] = $this->mergeArr($rst['$and'],$larr, $rarr); return $rst; }else{//如果同层,直接把值都放到同层数组去 $rst = array_merge($this->exec($mat[1],$leftSame,true),$this->exec($mat[3],$rightSame,true)); return $rst; } }else if($op == "||"){ if(!$layer || $fromAnd){//如果不同层 $rst['$or'] = []; $larr = $this->exec($mat[1],$leftSame,false); $rarr = $this->exec($mat[3],$rightSame,false); $rst['$or'] = $this->mergeArr($rst['$or'],$larr, $rarr); }else{ $rst = []; $rst = array_merge($this->exec($mat[1],$leftSame,false),$this->exec($mat[3],$rightSame,false)); } return $rst; } } else{//如果最终已经分解成a=b的形式时,就在此解析 preg_match($this->reg2, $query,$matches); if(count($matches) >= 4){ $left = $matches[1]; $op = $matches[2]; $right = $matches[3]; $rst = []; if($op == "="){ if(is_numeric($right)){ $rst[$left] = (float)$right; }else{ $rst[$left] = $right; } }else{ if(!isset($rst[$left])){ $rst[$left] = []; } if(is_numeric($right)){ $rst[$left][$this->opMap[$op]] = (float)$right; }else{ $rst[$left][$this->opMap[$op]] = $right; } } return $rst; } } } function mergeArr($rst,$larr,$rarr){ foreach ($larr as $lk=>$lv){ $lcond = []; $lcond[$lk] = $lv; $rst[] = $lcond; } foreach ($rarr as $rk=>$rv){ $rcond = []; $rcond[$rk] = $rv; $rst[] = $rcond; } return $rst; } } ?>
好了,就这么多内容,我想应该会有人需要的
有什么问题直接留言吧
以上就介绍了写了一个PHP版本的MONGODB语法解析器,可以通过类似SQL的语法来进行查询,不知道有人需要不,分享一下吧,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

In this article, we will show you how to reorder multiple columns in PowerQuery by dragging and dropping. Often, when importing data from various sources, columns may not be in the desired order. Reordering columns not only allows you to arrange them in a logical order that suits your analysis or reporting needs, it also improves the readability of your data and speeds up tasks such as filtering, sorting, and performing calculations. How to rearrange multiple columns in Excel? There are many ways to rearrange columns in Excel. You can simply select the column header and drag it to the desired location. However, this approach can become cumbersome when dealing with large tables with many columns. To rearrange columns more efficiently, you can use the enhanced query editor. Enhancing the query

ReactQuery database plug-in: Methods to implement data import and export, specific code examples are required. With the widespread application of ReactQuery in front-end development, more and more developers are beginning to use it to manage data. In actual development, we often need to export data to local files or import data from local files into the database. In order to implement these functions more conveniently, you can use the ReactQuery database plug-in. The ReactQuery database plugin provides a series of methods

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.
