我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。

喜欢的东西:

db.users.findOne({$contains:{"username":"son"}})

这可能吗?


当前回答

这是完成这项任务最简单的方法

如果您希望查询区分大小写

db.getCollection("users").find({'username':/Son/})

如果您希望查询不区分大小写

db.getCollection("users").find({'username':/Son/i})

其他回答

由于Mongo shell支持正则表达式,这是完全可能的。

db.users.findOne({"username" : /.*son.*/});

如果我们想让查询不区分大小写,我们可以使用"i"选项,如下所示:

db.users.findOne({"username" : /.*son.*/i});

参见:http://www.mongodb.org/display/DOCS/Advanced + # AdvancedQueries-RegularExpressions查询

从2.4版开始,您可以在字段上创建一个文本索引来进行搜索,并使用$text操作符进行查询。

首先,创建索引:

db.users。createIndex({"username": "text"})

然后,搜索:

db.users。查找({$text: {$search: "son"}})

基准测试(~150K文档):

Regex(其他答案)=> 5.6-6.9秒 文本搜索=> .164-。201秒

注:

A collection can have only one text index. You can use a wildcard text index if you want to search any string field, like this: db.collection.createIndex( { "$**": "text" } ). A text index can be large. It contains one index entry for each unique post-stemmed word in each indexed field for each document inserted. A text index will take longer to build than a normal index. A text index does not store phrases or information about the proximity of words in the documents. As a result, phrase queries will run much more effectively when the entire collection fits in RAM.

https://docs.mongodb.com/manual/reference/sql-comparison/

http://php.net/manual/en/mongo.sqltomongo.php

MySQL

SELECT * FROM users WHERE username LIKE "%Son%"

MongoDB

db.users.find({username:/Son/})

如何在RegExp匹配中忽略HTML标签:

var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';

var rx = '';
searchString.split(' ').forEach(e => {
  rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});

rx = new RegExp(rx, 'igm');

console.log(text.match(rx));

这可能很容易变成一个MongoDB聚合过滤器。

您可以使用以下代码来实现。

db.users.findOne({"username" : {$regex : "son"}});