How to query MongoDB with “like”?

后端 未结 30 2135
予麋鹿
予麋鹿 2020-11-21 05:51

I want to query something with SQL\'s like query:

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

How to do I achieve the same in

30条回答
  •  鱼传尺愫
    2020-11-21 06:09

    It seems that there are reasons for using both the javascript /regex_pattern/ pattern as well as the mongo {'$regex': 'regex_pattern'} pattern. See: MongoBD RegEx Syntax Restrictions

    This is not a complete RegEx tutorial, but I was inspired to run these tests after seeing a highly voted ambiguous post above.

    > ['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" }
    

提交回复
热议问题