MongoDB regular expression and its application _ regular expression

Source: Internet
Author: User
Tags mongodb regular expression

Regular expressions are often used to search for any pattern or text in a string in all languages. MongoDB also provides a string pattern of regular expression functionality using regular Expression $regex operator. MongoDB uses Pcre (Perl-compatible regular expressions) as a regular expression language.

Unlike text search, we do not need to make any configuration or command to use regular expressions directly.

Consider the collection of posts that contain the label after the text, which is structured as follows:

{
 "Post_text": "Enjoy the MongoDB articles on Yiibai",
 "tags": [
  "MongoDB",
  "Yiibai"
 ]
}

Using regular expression expressions

The following regular expression query searches for all posts that contain string yiibai.com:

Copy Code code as follows:

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

The same query can also be written as:

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

Using regular expressions is case-insensitive

In order for the search to be case-insensitive, we use $options with the value parameter $i. The following command searches the string: yiibai.com, regardless of case:

Copy Code code as follows:

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

The result of this query realignment is that the word Yiibai document is included in the size, as follows:

{
 "_id": ObjectId ("53493d37d852429c10000004"),
 "Post_text": "hey! This is me post on Yiibai ", 
 tags": ["Yiibai"]
} 

An array element that uses a regular expression:

We can also use the array word Ha Zheng expression concept. At this time we realize the function of the label is particularly important. So, if you want to search for all posts (whether tutorial or tutorials or Tutorialjava or tutorialphp) with a label to start with a phrase tutorial, you can use the following code:

Copy Code code as follows:

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

To optimize the regular expression query:

If the document field is indexed, the query uses matching regular expressions that use index values. This makes the search very fast and the regular expression is relative to scanning the entire collection.

If the regular expression is a prefix expression, all matches are started with a string of characters. For example, if the regular expression is ^tut, the query has only a search for those starting string tut.

The application of MongoDB regular expression

Regular expressions are fully supported in MongoDB, and operators can be used in general queries $regex

Db.lnmopy.find ({' Name ':/*.lnmopy.com/i})
Db.lnmopy.find ({' name ': {$regex: ' *.lnmopy.com ', $options: ' I '}})

The above two completely equivalent, you can directly to the field (field) in the example of the ' name ' key, the use of regular expressions or operators, the optional item is I, that is, ignore case.
With regard to the regular option, MongoDB and other language standards are slightly different and have their own standards.

Optional value for $options

I ignores case;

M multiple-line lookup, which has no effect if there is no newline symbol (for example \ n) in the content or there is no (start/end) on the structure;
x whitespace characters are completely ignored in addition to being escaped or outside of the character class, and all characters, including both ends, that are not escaped from the character class and the next line break are ignored;

S-dot meta character (.) matches all characters, including line breaks

Let's say we have a database named Mongodemo

Use Mongodemo

There is a collection named Lnmopy in the database

Db.lnmopy.find ()

The following data are available:

{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Www.lnmopy.com", "Site": "website", "tag": "L,n,m,o,p,y"}
{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Demo.lnmopy.com", "Site": "Unknown", "tag": "D,e,m,o"}
{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Welcome.lnmopy.com", "Site": "website", "tag": "W,e,l,c,o,m,e" }

MongoDB Regular expressions only support JavaScript native notation (such as/*.lnmopy.com/i) for I and M. If you use the X and S options, you must specify the option in $options by using the $regex operator.

Use update actions for regular expressions:

Db.lnmopy.update ({' Name ':/*.lnmopy.com/i}, {$set: {' site ': ' Www.lnmopy.com '}});

This means looking for an entry in the collection named "Lnmopy" in the current database that matches the "/*.lnmopy.com/i" regular, and only updates the "Site" field to "Www.lnmopy.com", which updates only one piece of data, if not $ Set, then this record will only be left with your updated part and default Objectid, which can be said to be replaced. If you want to replace all, you can add parameters:

Db.lnmopy.update ({' Name ':/*.lnmopy.com/i}, {$set: {' site ': ' Www.lnmopy.com '}}, False, True);

The arguments are in order, false is Upsert, and if not, the new one is inserted. True is multi multiple records update, all matches to the result. or specify {multi:true} directly:
Db.lnmopy.update ({' Name ':/*.lnmopy.com/i}, {$set: {' site ': ' Www.lnmopy.com '}}, {multi:true});
This updates all the "site" fields to "www.lnmopy.com".

I designed the field "tag" There is a flaw, that is a word, now each letter is "," separated. Similar problems exist in the actual work, because the batch transforms the data, or other program improper operation, or the business needs change and so on the reason needs to carry on the regular batch processing to some fields, the MongoDB general updating method is not possible, then needs to use the JavaScript statement.

Regular expression replaces query result ', ' as '

Db.lnmopy.find (). ForEach (function (u) {u.tag = U.tag.replace (/\,/, ""); Db.lnmopy.save (U); } );

Final implementation

Db.lnmopy.find ()

Displays the following data:

{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Www.lnmopy.com", "Site": "www.lnmopy.com", "tag": "Lnmopy"}
{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Demo.lnmopy.com", "Site": "www.lnmopy.com", "Tag": "Demo"}
{"_id": ObjectId ("502dd63d16a25b1ff6000000"), "name": "Welcome.lnmopy.com", "Site": "www.lnmopy.com", "tag": "Welcome "}

PostScript: JavaScript is a major feature of the MongoDB, but also the advantages of many complex queries and processing can be implemented with JavaScript, it should be noted that JavaScript efficiency is low, in principle, should try to avoid in the main business logic to use heavily. By analogy, JavaScript is the equivalent of Oracle's stored procedures, and it's not surprising that 10gen (MongoDB's development team) comes from Oracle. about how to use more complex JavaScript, which will be written later.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.