码农家园

关闭
导航

关于sql:如何用“喜欢”查询MongoDB?


mongodbmongodb-querysqlsql-like

How to query MongoDB with “like”?

我想用SQL的like查询查询:

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

如何在MongoDB中实现相同的目标?我在文档中找不到like的操作员。

相关讨论

  • 参见mongodb的docs:advanced querys——正则表达式mongodb.org/display/docs/…
  • 你的问题至少得到了类似操作标签的5票。我可以请求您建议使用类似SQL的同义词吗?
  • 此链接可以帮助您goo.gl/gdtyk8


那必须是:

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

或者,类似:

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

您要查找的是某处包含"m"的内容(SQL的"EDOCX1"(1)运算符相当于regexp的"EDOCX1"(2)),而不是将"m"锚定到字符串开头的内容。

相关讨论

  • 用regex搜索是否昂贵?
  • @自由风:不,不贵。
  • 实际上,这要看情况而定。如果查询不使用索引,并且必须进行表扫描,那么它肯定是昂贵的。如果执行的是"starts with"regex查询,那么可以使用索引。最好运行explain()来查看发生了什么。
  • 如果不是锚定在绳子的开头,那就有点贵了。但同样,SQL中的LIKE查询也是如此。
  • 所以只要锚定在绳子的开头就可以了?那么酷。这是否意味着我们需要补充^
  • @凯尔:LIKE和REGEX在计算上的差异是完全无关的;这永远不会成为瓶颈。查询时间取决于必须分析的文档数(即是否匹配字符串的开头和是否可以使用索引),而不是取决于字段比较本身。
  • 如果字符串中有特殊字符,如db.users.find("name":/.*mmm$mmm.*/),该怎么办?谢谢
  • 我不明白……它只返回集合中的所有项:s
  • 也不要忘记像/m/i这样的修改器。
  • 我会加上regex i javascript db.users.find({"name": { $regex: /m/i } })
  • 这个在蒙古包里会是什么样子?... WHERE name Like '% txt %' OR name Like 'txt %'
  • 此链接可以提供帮助
  • 我试过用PHP将您的查询命名为$query = array('evnt_name' => array("\$regex"=>"/Cr/")); $db->mycollname->find($query),但没有得到记录。我做的对吗?@ DoronSegal
  • 另一种成本更低的方法是创建搜索索引,请查看stackoverflow.com/a/50363402/3284463
  • @Doronsegal小心使用不区分大小写的正则表达式。不区分大小写的regex将不使用索引,即使它们被固定到字符串的开头,并且即使索引本身通过排序规则不区分大小写,即使从Mongo 4.0开始。更多阅读:docs.mongodb.com/manual/reference/operator/query/regex/…


1
2
3
4
5
db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

db.users.find({name: /a/})  //LIKE '%a%'

外出:保罗,帕特里克

1
db.users.find({name: /^pa/}) //LIKE 'pa%'

外出:保罗,帕特里克

1
db.users.find({name: /ro$/}) //LIKE '%ro'

外:佩德罗

相关讨论

  • 很好的实例!我发现found this with check:空间和端元/)/
  • 如何找到你的entries for name?在wildcard for the SQL *或?select name from users;something that does the which lists的只是用户?
  • anon58192932 of entries to"显示在"名称"字段中只在表命名"users"项目,你可以使用()method by setting of Fields,你想要的值1。which are not在上述领域项目(Will not be)fetched除了_ ID。ID的默认模式是印制_场你可以suppress by which把价值在0 _项目(ID)的方法。什么样db.collection.find .project(name):({ 0 } _ ID号:1,.toarray(function(){ console.log(ERR,文档)文档(文档););}回调参考this);///教程手册- docs.mongodb.com & hellip;


在

  • 使用python的pymongo
  • Mongoose使用node.js
  • Jongo,使用Java
  • 氧化镁

你可以做到:

1
db.users.find({'name': {'$regex': 'sometext'}})
相关讨论

  • 它对区分大小写的搜索很有效,你能告诉我怎样才能使它有效地执行不区分大小写的搜索吗?
  • 对于%sometext%来说,regex是什么?
  • @Tahiryasin如果你还想知道,不区分大小写的搜索应该是这样的:db.users.find({'name': {'$regex': 'sometext', '$options': 'i'}})。
  • 我用mgo在golang解决了这个问题,它的代码很简单,选择器:=bson.m"technician":bson.m"$regex":tech
  • @SandUnpriyanka MGO库有一个内置的regex类型,您应该使用bson.M{"technician", bson.RegEx{Pattern: tech}}(但一定要确保tech已被净化,否则您会有regex注入漏洞!)
  • 我在TalendOpenStudio中编写了一个MongoQuery,这很有魅力。谢谢您!
  • 此方法在MLAB的Web界面中有效。


在PHP中,可以使用以下代码:

1
$collection->find(array('name'=> array('$regex' => 'm'));
相关讨论

  • python+mongoengine:people=people.objects.raw_query('name':'$regex':'m')
  • 如果您的regex值源自用户输入(例如,筛选表单),并且您不希望将该值本身作为regexp,则可以对其应用preg_quote()。
  • 我刚刚意识到这一点,但这实际上是错误的答案,即使它是次优的,您应该通过mongoregex使用实际的bson regex对象,$regex与$in等某些命令存在兼容性问题。
  • 如果值存储在变量中,那么此语法很有用,因此查询可以(在ruby中)编写为:$collection.where(field => {"$regex" => value})。
  • 但是为什么不能使用数组文本呢?
  • 我很高兴我不用再使用PHP了,所以上面的语法实在是太烦人了。


在Mongo中,您可以使用regex。

例如:db.users.find({"name": /^m/})。

相关讨论

  • 我认为这只显示名称值以"m"开头的文档


答案已经很多了。我给出了使用regex进行字符串搜索的不同类型的需求和解决方案。

您可以使用包含单词i.e like的regex。也可以使用$options => i进行不区分大小写的搜索。

包含string。

1
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

不包含仅包含regex的string

1
db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

精确不区分大小写string。

1
db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

从string开始

1
db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

以string结尾

1
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

请将此作为书签保存,并为您可能需要的任何其他更改提供参考。


如果使用node.js,则说明可以编写以下内容:

1
2
3
db.collection.find( { FIELD: /acme.*corp/i } );
//OR
db.collection.find( { FIELD: { $regex: 'acme.*corp', $options: 'i' } } );

此外,您还可以写下:

1
db.collection.find( { FIELD: NEW REGEXP('acme.*corp', 'i') } );
相关讨论

  • Ruby中的类似语法:collection.where(field => Regexp.new(value))。


您有两个选择:

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

或

1
db.users.find({"name": {"$regex":"string","$options":"i"}})

在第二个选项中,您有更多的选项,比如"i",可以使用不区分大小写的选项来查找。关于"字符串",您可以使用像".string."(%string%)或"string.*"(string%)和".*string")(%string)这样的方法。可以根据需要使用正则表达式。

享受!


你已经得到答案了,但是要匹配regex和case不敏感

您可以使用以下查询

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

/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。


对于node.js中的mongoose

1
db.users.find({'name': {'$regex': '.*sometext.*'}})

像php mongo。我对php mongo有几个问题。我发现连接regex参数有助于在某些情况下php mongo find字段以开头。我想我会在这里发表文章,为更受欢迎的主题做贡献。

例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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)
相关讨论

  • 在回答对As和文本(previous search index)将美元给更好的解决方案与基准的regex?比较法对美元。stackoverflow.com check this for reference 10610131 /链接/问题/ & hellip;。是它可能与美元指数法对实施"订单和MongoDB的PHP文本


您可以使用2.6 MongoDB的新功能:

1
2
3
4
5
6
7
8
db.foo.insert({DESC:"This is a string with text"});
db.foo.insert({DESC:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});
相关讨论

  • 注释的文本本身mongodb'在线搜索默认只在工厂模式的话,我会打这类"this is a值与文本字符串"This is,but not"与subtext字符串"。我知道这不是那么"类的类"sql'社。
  • rocketmonkeys其真。"for something like"类社会使用正则表达式"芒果社你美元。


在nodejs项目中使用mongoose,使用like查询

1
2
3
4
5
6
7
8
9
10
11
var USER = mongoose.model('User');

var searchQuery={};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
USER.find(searchQuery, FUNCTION(error, USER) {
                IF(error || USER === NULL) {
                    RETURN res.status(500).send(error);
                }
                RETURN res.status(200).send(USER);
            });
相关讨论

  • 可以使用查询如何样?我想这工作:searchQuery.product_name = '/'+req.query.search.value+'/i';but not
  • 可以尝试searchQuery.product_name= {$regex: req.query.search.value, $options: 'i'};类:
  • 你拯救我的生命吧。你能解释什么是正则表达式。小美元和美元期权?
  • 你可以看if(req.query.search.value){ searchQuery.product_name = {$regex: req.query.search.value, $options: 'i'}; searchQuery.sale_amount = {$regex: req.query.search.value, $options: 'i'}; searchQuery.sale_person = {$regex: req.query.search.value, $options: 'i'}; searchQuery.department_name = {$regex: req.query.search.value, $options: 'i'}; searchQuery.sale_date = {$regex: req.query.search.value, $options: 'i'}; }this is not。为什么工作?
  • 正则表达式搜索为你的好$regex: 'value' generate值均值和$options: 'i'房屋不敏感。你的代码不工作都因为你same value for used as that different财产法和fulfill condition that should not布尔与你的数据库收集的。
  • 问题是_ that is the amount is number,盐型,当它停止工作new productsearched类。你能PLS和号蓝晶石可以搜索过?
  • battle.find { {"attacker _王":"正则表达式"req.query.king美元美元,"::""期权"})/金="罗伯"here is an empty结果回来,但battle.find { {"attacker _王":"regex"$"$,"罗伯":期权":"归来"(the correct)}。我是在这里失踪


在SQL中,"like"查询如下所示:

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

在MongoDB控制台中,如下所示:

1
2
3
db.users.find({"name": /m/})     // NOT JSON formatted

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

另外,pretty()方法将在所有生成格式化JSON结构的地方使用,这种结构更具可读性。


在Go和MGO驱动程序中:

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

其中,result是请求后类型的结构实例

相关讨论

  • 在文字领域avoid unkeyed PLS,我bson:RegEx{Pattern:"m", Options:"i"}instead


可以使用WHERE语句构建任何JS脚本:

1
db.myCollection.find( { $where:"this.name.toLowerCase().indexOf('m') >= 0" } );

参考:http://docs.mongodb.org/manual/reference/operator/where/

相关讨论

  • $where效率很低。执行完全收集扫描:(
  • 我承认我还没有做任何性能测试。
  • 啊,没问题,我是这么说的:D


使用MongoDB Compass,需要使用严格的模式语法,例如:

1
{"text": {"$regex":"^Foo.*","$options":"i" } }

(在MongoDB指南针中,使用"而不是'很重要)


使用如下匹配的正则表达式。"i"表示不区分大小写。

1
2
3
4
5
6
7
8
9
10
11
12
var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", NEW BsonRegularExpression("ABCD","i")),
         Query.Matches("strVal", NEW BsonRegularExpression("4121","i")));

var queryB = Query.Or(
       Query.Matches("strName", NEW BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", NEW BsonRegularExpression("33156","i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);

like查询如下所示

1
db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

对于scala reactiveMogo API,

1
2
3
val query = BSONDocument("title" -> BSONRegex(".*"+name+".*","")) //LIKE
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]


REGEX是昂贵的工艺。

另一种方法是创建文本索引,然后使用$search搜索它。

创建要使其可搜索的字段的文本索引:

1
db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

1
2
3
db.collection.find({
  '$text'=>{'$search':"The string"}
})
相关讨论

  • 完美的解决方案…Regex的价格太贵了。使用20M文档的数据集时,性能差异非常明显(这是一种轻描淡写的做法)
  • 这似乎只适用于整个单词。
  • 实际上,这只适用于整个单词,请参见docs.mongodb.com/manual/core/index text/index entries


如果您想在mongo中进行"like"搜索,那么您应该使用$regex,使用该查询将

db.product.find({name:{$regex:/m/i}})

更多信息,您也可以阅读文档。https://docs.mongodb.com/manual/reference/operator/query/regex网站/


如果您使用的是SpringDataMongoDB,那么可以这样做:

1
2
3
4
String tagName ="m";
Query query = NEW Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));

似乎有理由同时使用javascript /regex_pattern/模式和mongo {'$regex': 'regex_pattern'}模式。参见:mongobd regex语法限制

这不是一个完整的regex教程,但是在看到上面一个高度模糊的帖子后,我被启发去运行这些测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
> ['abbbb','bbabb','bbbba'].forEach(FUNCTION(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{"val" :"abbbb" }
{"val" :"bbabb" }
{"val" :"bbbba" }

> db.test_collection.find({val: /.*a.*/})
{"val" :"abbbb" }
{"val" :"bbabb" }
{"val" :"bbbba" }

> db.test_collection.find({val: /.+a.+/})
{"val" :"bbabb" }

> db.test_collection.find({val: /^a/})
{"val" :"abbbb" }

> db.test_collection.find({val: /a$/})
{"val" :"bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{"val" :"bbbba" }

由于MongoShell支持regex,这是完全可能的。

1
db.users.findOne({"name" : /.*sometext.*/});

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

1
db.users.findOne({"name" : /.*sometext.*/i});


我找到了一个免费的工具来将mysql查询翻译成mongodb。http://www.querymongo.com/我查了好几个问题。正如我看到的,几乎所有的都是正确的。根据这一点,答案是

1
2
3
db.users.find({
   "name":"%m%"
});

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);
相关讨论

  • 好!there is to get the Whole document方式匹配?使聚集,使茶或查询的框架跟文给我吗?at the比赛类:北{"_id" : ObjectId("5aba5ad988385120a01b1ac2"),"fieldExists" : 4 }矩
  • 在项目的实习项目美元只是你想要什么


使用带变量的模板文本也可以:

{"firstname": {$regex : `^${req.body.firstname}.*` , $options: 'si' }}

相关讨论

  • 这是搜索ig,从开始前-如果"firstname"包含testlast,如果我搜索"last",它不会给出结果。


MongoRegex已被弃用。使用mongodbson
egex

1
2
3
4
$regex = NEW MongoDB\BSON
egex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
相关讨论

  • important to that this这是已知的mongoregex to the"是指在PHP的类。not to this question is Very about which相关节点。this should probably be a comment或更好-在喃喃自回答问题分开。


1
db.customer.find({"customerid": {"$regex":"CU_00000*","$options":"i"}}).pretty()

当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。希望有帮助!!!!


全名,如"last",状态为"='pending",介于两个日期之间:

1
2
3
4
5
db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      STATUS:"Pending",
      fullName:/LAST/}).pretty();

status=='pending'和orderid,如'pha876174':

1
2
3
4
db.orders.find({
     STATUS:"Pending",
     orderId:/PHA876174/
     }).pretty();

1
2
3
4
>> db.car.distinct('name')
["honda","tat","tata","tata3" ]

>> db.car.find({"name":/. *ta.* /})
相关讨论

  • 哇,this is probably安奇异的回音。亲爱的,到制定在线?
  • 使用你的解决方案的问题的答案在the given example。Do not that to create a随机场景似乎重叠在功能性和期望它似乎清楚。


您还可以使用通配符过滤器,如下所示:

1
{"query": {"wildcard": {"lookup_field":"search_string*"}}}

一定要使用*。


如果您使用的是PHP,那么可以使用MongoDB_DataObject包装器,如下所示:

1
2
3
4
5
6
7
$model = NEW MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

或:

1
2
3
4
5
6
7
8
9
$model = NEW MongoDB_DataObject('users);

$model->whereAdd("name like '
%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}

  • 关于MySQL:如何在PHP中防止SQL注入?
  • 关于sql:我可以将多个MySQL行连接到一个字段中吗?
  • 关于SQL:如何限制Oracle查询在排序后返回的行数?
  • 如何从SQL Server中的select执行update?
  • 关于mysql:SQL仅选择列上具有最大值的行

Copyright ©  码农家园 联系:[email protected]