Using Regex – MongoDB array string field value length query

Using Regex MongoDB nested array string field value length query

Today in this article we will write a Using Regex – MongoDB array string field value length query which will give us the details of the record based on field value length including greater than or less than or equal

We will cover below query types below using the Regex MongoDB query,

We already looked at a simple way of adding or updating a new field to the document in our previous MongoDB sample series.

Getting started

Here below is a sample schema or document we shall use for array object with field length query and will cover less than or greater than length query for field value “Books.category.value” field.

Below by value field is of type string and we will get all records where such field length is less than or greater than the specified size.

Here is the query pattern explained

RegExp – MongoDB array string field value greater than query

Example

{"Books.category.value": RegExp('^.{5,}$')}

The above query returns all the records where the string length of the “value” field is greater than 5.

RegExp MongoDB nested array string field value greater than query

RegExp – MongoDB array string field value less than query

Example

{"Books.category.value": RegExp('^.{0,5}$')}

RegExp MongoDB nested array string field value less than query

The above query returns all the records where the string length of the “value” field is less than 5.

RegExp – MongoDB array string field value greater than and Less than query

Example

{"Books.category.value": RegExp('^.{3,5}$')}

RegExp MongoDB nested array string field value greater than and Less than query

The above query returns all the records where the string length of the “value” field is greater than 5 characters and less than 10 characters.

Checking alphanumeric string length

^[a-zA-Z0-9]{5,}$  

Note: The above query can be used for integer type or string type as required.

Please update the query per your requirements.

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *