Home >Database >Mysql Tutorial >Introduction to how mgo specifies the string length to find data (code)

Introduction to how mgo specifies the string length to find data (code)

不言
不言forward
2019-03-23 16:26:002681browse

The content of this article is about the method of mgo specifying the string length to find data (code). It has certain reference value. Friends in need can refer to it. I hope it will help You helped.

At work, we occasionally filter some data based on the length of the string field. At this time, we may use regular expressions, or we can use mongodb's $where. Regular expressions are written correctly in different languages. There are some differences, so I’ll record them here.

If you are looking for data with a comment field string length greater than 10, the mongodb command line is written as follows:

$where is written as:

find({"comment":{"$exists":true},"$where":"this.comment.length>10"})

Regular expression is written as:

find({"comment":{"$regex":/^.{10,}$/}})

The writing method in go language is as follows:

$where writing method:

collection.Find(bson.M{"comment": bson.M{"$exists": true}, "$where": "this.comment.length > 10"})

Regular expression writing method:

collection.Find(bson.M{"comment": bson.M{"$exists": true, "$regex": bson.RegEx{`^.{10,}$`, ""}}})

Other conditions regular:

^.{n,m}$ n <= length<= m
^.{n}$ length= n

this length It is the length of characters. For example, the length of "regular expression" is 5

As for search performance, it is said on the Internet that regular expression has better performance than $where. When the amount of data is not large, a simple test shows that regular expression has better search performance. One point, I will have time to do further research later

This article has ended here. For more other exciting content, you can pay attention to the mongodb video tutorial column on the PHP Chinese website !

The above is the detailed content of Introduction to how mgo specifies the string length to find data (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete