user1710631
user1710631

Reputation: 113

How do I make searches on Mongodb using wildcard characters?

For example if my keyword is "all", I would like MongoDb to return all the documents in the given field containing the words "all" like "edgar allan poe" or "whitney hall". How do I do that in MongoDb? I've been stuck here for days so any help would be greatly appreciated :)

Upvotes: 11

Views: 20147

Answers (1)

c.P.u1
c.P.u1

Reputation: 17094

By using a regular expression. MongoDb has a $regex operator.

db.authors.find({name: {$regex: 'all', $options: 'i'}});

Regex operations cannot use indexes, so find() operations won't be efficient. An index can only be used for prefix(starts with) and case-sensitive matches like this query:

db.authors.find({name: {$regex: '^a'});

Upvotes: 18

Related Questions