我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

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

其他回答

对于PHP mongo Like。

我对PHP mongo有几个问题。我发现串联正则表达式参数在某些情况下会有所帮助——PHP mongo find字段以开头。

例如

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]

>> db.car.find({"name":/. *ta.* /})

这必须是:

db.users.find({"name": /.*m.*/})

或类似:

db.users.find({"name": /m/})

您正在查找某个地方包含“m”的内容(SQL的“%”运算符相当于正则表达式“.*”),而不是在字符串开头锚定了“m”。

注意:MongoDB使用的正则表达式比SQL中的“LIKE”更强大。使用正则表达式,您可以创建任何您想象的模式。

有关正则表达式的详细信息,请参阅正则表达式(MDN)。

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);

在Go和mgo驱动程序中:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

其中结果是所查找类型的结构实例。