Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 267
user1710631 Avatar asked Jun 28 '13 03:06

user1710631


People also ask

How do I use wildcard search in MongoDB?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

Can Wildcards be used with field searches?

A wildcard character is used to search for a partial value in a field when you do not know the entire value. You place the wildcard where the unknown characters occur. You can use more than one wildcard character in a single search.

What is the wildcard character for searching?

You can use the asterisk (*) anywhere in a character string. wh* finds what, white, and why, but not awhile or watch. Matches a single alphabet in a specific position.

How do you use a wildcard in a database?

Match a character within a pattern Open your query in Design view. In the Criteria cell of the field you want to use, type the operator Like in front of your criteria. Replace one or more characters in the criteria with a wildcard character. For example, Like R?


1 Answers

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'});
like image 95
c.P.u1 Avatar answered Oct 24 '22 08:10

c.P.u1