3.41. MongoDB regular expression

发布时间 : 2025-10-25 13:34:24 UTC      

Page Views: 10 views

A regular expression uses a single string to describe and match a series of strings that conform to a syntactic rule.

Many programming languages support string manipulation using regular expressions.

MongoDB usage $regex Operator to set the regular expression that matches the string.

MongoDB uses PCRE (Perl Compatible Regular Expression) as the regular expression language.

Unlike full-text retrieval, we don’t need to do any configuration to use regular expressions.

Consider the following posts The document structure of the collection that contains the article content and tags:

{ "post_text": "enjoy the mongodb articles on runoob", "tags": [ "mongodb", "runoob" ] } 

3.41.1. Use regular expressions

The following command uses regular expressions to find articles that contain runoob strings:

>db.posts.find({post_text:{$regex:"runoob"}}) 

The above query can also be written as:

>db.posts.find({post_text:/runoob/}) 

3.41.2. Case-insensitive regular expression

If retrieval needs to be case-insensitive, we can set $options to $I.

The following command looks for the case-insensitive string runoob:

>db.posts.find({post_text:{$regex:"runoob",$options:"$i"}}) 

All data containing the string runoob is returned in the collection, and is case-insensitive:

{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on runoob", "tags" : [ "runoob" ] } 

3.41.3. Array elements use regular expressions

We can also use regular expressions in array fields to find content. This is very useful for tag implementation. If you need to find tag data that starts with run (ru or run or runoob), you can use the following code:

>db.posts.find({tags:{$regex:"run"}}) 

3.41.4. Optimize regular expression query

  • If the fields in your document are indexed, then using the index to find all the data queries is faster than regular expression matching.

  • If the regular expression is a prefix expression, all matching data will start with the specified prefix string. For example, if the regular expression is ^ tut, the query will look for a string that begins with tut.

There are two points to note when using regular expressions:

Variables are used in regular expressions. Be sure to use eval to convert the combined string, and you can’t pass the string into the expression directly after concatenation. Otherwise, there is no wrong information, but the result is empty! Examples are as follows:

var name=eval("/" + 变量值key +"/i"); 

The following is a fuzzy query that contains title keywords and is not case-sensitive:

title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"} 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。