How to query MongoDB with “like”?

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

    In

    • PyMongo using Python
    • Mongoose using Node.js
    • Jongo, using Java
    • mgo, using Go

    you can do:

    db.users.find({'name': {'$regex': 'sometext'}})
    
    0 讨论(0)
  • 2020-11-21 06:13

    You can use where statement to build any JS script:

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

    Reference: http://docs.mongodb.org/manual/reference/operator/where/

    0 讨论(0)
  • 2020-11-21 06:15

    Use regular expressions matching as below. The 'i' shows case insensitivity.

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

    That would have to be:

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

    or, similar:

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

    You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*'), not something that has "m" anchored to the beginning of the string.

    note: mongodb uses regular expressions which are more powerful than "LIKE" in sql. With regular expressions you can create any pattern that you imagine.

    For more info on regular expressions refer to this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

    0 讨论(0)
  • 2020-11-21 06:17

    Using template literals with variables also works:

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

    0 讨论(0)
  • 2020-11-21 06:20

    If you want 'Like' search in mongo then you should go with $regex by using this query will be

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

    for more you can read the documentation as well. https://docs.mongodb.com/manual/reference/operator/query/regex/

    0 讨论(0)
提交回复
热议问题