php 如何使“LIKE”查询在 MongoDB 中工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5798098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make "LIKE" query work in MongoDB?
提问by jM2.me
I have a list of street names and I want to select all that start with "Al". In my MySQL I would do something like
我有一个街道名称列表,我想选择所有以“Al”开头的名称。在我的 MySQL 中,我会做类似的事情
SELECT * FROM streets WHERE "street_name" LIKE "Al%"
How about MongoDB using PHP?
使用 PHP 的 MongoDB 怎么样?
回答by ceejayoz
Use a regular expression:
使用正则表达式:
db.streets.find( { street_name : /^Al/i } );
or:
或者:
db.streets.find( { street_name : { $regex : '^Al', $options: 'i' } } );
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
Turning this into PHP:
将其转换为 PHP:
$regex = new MongoRegex("/^Al/i");
$collection->find(array('street_name' => $regex));
回答by Homer6
See: http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart
参见:http: //www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart
Also, highly recommend just using the native mongodb connector from PHP instead of a wrapper. It's way faster than any wrapper.
此外,强烈建议仅使用 PHP 中的本机 mongodb 连接器而不是包装器。它比任何包装器都快。
回答by Ruslan Terekhov
here is my working example:
这是我的工作示例:
<?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
回答by Albert s
MongoRegex has been deprecated.
Use MongoDB\BSON\Regex
MongoRegex 已被弃用。
使用MongoDB\BSON\Regex
$regex = new MongoDB\BSON\Regex ( '^A1');
$cursor = $collection->find(array('street_name' => $regex));
//iterate through the cursor
回答by Anil Singh
<?php
$mongoObj = new MongoClient();
$where = array("name" => new MongoRegex("^/AI/i"));
$mongoObj->dbName->collectionName->find($where);
?>
回答by koe
$collection.find({"name": /.*Al.*/})
$collection.find({"name": /.*Al.*/})
or, similar,
或者,类似的,
$collection.find({"name": /Al/})
$collection.find({"name": /Al/})
You're looking for something that contains "Al" somewhere (SQL's '%' operator is equivalent to regexps' '.*'), not something that has "Al" anchored to the beginning of the string.
您正在寻找某处包含“Al”的内容(SQL 的 '%' 运算符相当于正则表达式''.*'),而不是将“Al”锚定到字符串开头的内容。
回答by andranikasl
You can also do something like this
你也可以做这样的事情
['key' => ['$regex' => '(?i)value']]