2011-04-27 57 views

回答

12

使用正則表達式:

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

0

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

,或者類似的,

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

你要找的東西,包括 「基地」 的地方(SQL的 '%' 運算符相當於正則表達式'。*'),而不是將「Al」錨定到字符串的開頭。

1

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

$regex = new MongoDB\BSON\Regex ('^A1'); 
$cursor = $collection->find(array('street_name' => $regex)); 
//iterate through the cursor 
0
<?php 
$mongoObj = new MongoClient(); 
$where = array("name" => new MongoRegex("^/AI/i")); 
$mongoObj->dbName->collectionName->find($where); 
?> 

View for more details

1

這是我的工作例如:

<?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