How to query MongoDB with “like”?

后端 未结 30 2669
予麋鹿
予麋鹿 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条回答
  •  萌比男神i
    2020-11-21 06:29

    There are already many answers. I am giving different types of requirements and solutions for string search with regex.

    You can do with regex which contain word i.e like. Also you can use $options => i for case insensitive search

    Contains string

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

    Doesn't Contains string only with regex

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

    Exact case insensitive string

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

    Start with string

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

    End with string

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

    Keep this as a bookmark, and a reference for any other alterations you may need.

提交回复
热议问题