# db.RegExp

From base library 2.3.2 (wx-server-sdk 0.0.23) and later, the database supports query using regular expression. Developers can use a JavaScript native regular object in query statements or construct a regular object using the db.RegExp method and then perform a string match. Regular match of a field in a query condition requires that the value of the field be matched by the given regular expression. Note that the regular expression is not available in db.command (e.g. db.command.in).

Regular expression matching can meet the requirement of string matching, but is not suitable for matching/searching for long text/text with a large amount of data due to performance issues. In this case, a text search engine such as ElasticSearch can be used.

db.RegExp is defined as follows:

function RegExp(initOptions: IInitOptions): DBRegExp

interface IInitOptions {
  regexp: string // Regular expression, in string format
  options: string // flags, including i, m, and s, but no strong limit is applied to the client
}

options supports i, m, and s flags. Note that when constructing a JavaScript native regular object, only i and m flags are supported. To use the s flag, the db.RegExp constructor is required to construct a regular object. "flag" is defined as below:

flag Description
i Case-insensitive search
m Multi-line search. Allows the start match character ^ to match the start of string and line and the end match character $ to match the end of string and line.
s Allows . to match newline characters

Example of basic usage:

// Native JavaScript object
db.collection('todos').where({
  description: /miniprogram/i
})

// Database regular object
db.collection('todos').where({
  description: db.RegExp({
    regexp: 'miniprogram',
    options: 'i',
  })
})

// "new" can also be used for construction
db.collection('todos').where({
  description: new db.RegExp({
    regexp: 'miniprogram',
    options: 'i',
  })
})