How to query MongoDB with “like”?

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

    You would use regex for that in mongo.

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

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

    In Go and the mgo driver:

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

    where result is the struct instance of the sought after type

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

    MongoRegex has been deprecated.
    Use MongoDB\BSON\Regex

    $regex = new MongoDB\BSON\Regex ( '^m');
    $cursor = $collection->find(array('users' => $regex));
    //iterate through the cursor
    
    0 讨论(0)
  • 2020-11-21 06:35

    In PHP, you could use following code:

    $collection->find(array('name'=> array('$regex' => 'm'));
    
    0 讨论(0)
  • 2020-11-21 06:35

    You can use the new feature of 2.6 mongodb:

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

    If you are using Spring-Data Mongodb You can do this in this way:

    String tagName = "m";
    Query query = new Query();
    query.limit(10);        
    query.addCriteria(Criteria.where("tagName").regex(tagName));
    
    0 讨论(0)
提交回复
热议问题