如何让使用PHP的MONGODB中的“LIKE”查询工作?

问题描述:

我有一个街道名称列表,我想选择所有以“Al”开头的。 在我的MySQL我会如何MongoDB的使用PHP这样做如何让使用PHP的MONGODB中的“LIKE”查询工作?

SELECT * FROM streets WHERE "street_name" LIKE "Al%" 

使用正则表达式:

db.streets.find({ street_name : /^Al/i }); 

或:

db.streets.find({ street_name : { $regex : '^Al', $options: 'i' } }); 

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

谈及到这个PHP:

$regex = new MongoRegex("/^Al/i"); 
$collection->find(array('street_name' => $regex)); 
+0

是的,但是在PHP怎么样? $ database-> streets-> find(array(“street”=>“/^Al/i”)); – 2011-04-27 00:52:39

+0

作为一个侧面的问题,这是如何比较原始速度?使用正则表达式来过滤数据集的想法让我感到有点...在mongodb上完成新手。 – 2011-04-27 00:53:18

+0

只要正则表达式以^开始(即匹配字符串的开头),就会使用索引。 – ceejayoz 2011-04-27 00:55:14

参见:http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

此外,强烈建议使用PHP的本地mongodb连接器而不是包装。它比任何包装都快。

http://php.net/class.mongodb

$collection.find({"name": /.*Al.*/})

,或者类似的,

$collection.find({"name": /Al/})

你要找的东西,包括 “基地” 的地方(SQL的 '%' 运算符相当于正则表达式'。*'),而不是将“Al”锚定到字符串的开头。

MongoRegex已被弃用。
使用MongoDB\BSON\Regex

$regex = new MongoDB\BSON\Regex ('^A1'); 
$cursor = $collection->find(array('street_name' => $regex)); 
//iterate through the cursor 

<?php 
$mongoObj = new MongoClient(); 
$where = array("name" => new MongoRegex("^/AI/i")); 
$mongoObj->dbName->collectionName->find($where); 
?> 

View for more details

这是我的工作例如:

<?php 
use MongoDB\BSON\Regex; 
$collection = $yourMongoClient->yourDatabase->yourCollection; 
$regex = new Regex($text, 's'); 
$where = ['your_field_for_search' => $regex]; 
$cursor = $collection->find($where); 
//Lets iterate through collection