How to query MongoDB with “like”?

后端 未结 30 2058
予麋鹿
予麋鹿 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:21

    You can query with a regular expression:

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

    If the string is coming from the user, maybe you want to escape the string before using it. This will prevent literal chars from the user to be interpreted as regex tokens.

    For example, searching the string "A." will also match "AB" if not escaped. You can use a simple replace to escape your string before using it. I made it a function for reusing:

    function textLike(str) {
      var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
      return new RegExp(escaped, 'i');
    }
    

    So now, the string becomes a case-insensitive pattern matching also the literal dot. Example:

    >  textLike('A.');
    <  /A\./i
    

    Now we are ready to generate the regular expression on the go:

    db.users.find({ "name": textLike("m") });
    
    0 讨论(0)
  • 2020-11-21 06:23

    Like Query would be as shown below

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

    for scala ReactiveMongo api,

    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]
    
    0 讨论(0)
  • 2020-11-21 06:24

    If using node.js, it says that you can write this:

    db.collection.find( { field: /acme.*corp/i } );
    //or
    db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );
    

    Also, you can write this:

    db.collection.find( { field: new RegExp('acme.*corp', 'i') } );
    
    0 讨论(0)
  • 2020-11-21 06:24

    In nodejs project and use mongoose use Like query

    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);
                });
    
    0 讨论(0)
  • 2020-11-21 06:24

    I found a free tool to translate MYSQL queries to MongoDB. http://www.querymongo.com/ I checked with several queries. as i see almost all them are correct. According to that, The answer is

    db.users.find({
        "name": "%m%"
    });
    
    0 讨论(0)
  • 2020-11-21 06:25

    For Mongoose in Node.js

    db.users.find({'name': {'$regex': '.*sometext.*'}})
    
    0 讨论(0)
提交回复
热议问题