MongoDB nested array string field value length query
Today this article will see how to write a MongoDB nested array string field value length query.
Today in this article, we will cover below aspects,
We will cover below query types,
- Greater than field value length
- Less than field value length
- Equal to the length of the field value
We shall see examples for MongoDB field query where we will get the records based on field length value greater than or less than of specified value. We will run field-length queries using CLI or Compass UI.
We already looked at a simple way of adding or updating a new field to the document in our previous MongoDB sample series.
We shall also see how to create a similar query using other languages like C# mongo driver.
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.
Mongo field length query using Mongo Shell or Compass UI
Here we will be using the below query to get the documents based on the value of the length of fields in the MongoDB Collection.
Nested array element finding and then getting its length can be done easily using below simple query as explained.
Pattern:
{ "$expr": { "$anyElementTrue": { "$map": { "input": { "$reduce": { "input": "$<YourFieldName(fully qualified field)>", "initialValue": [], "in": { "$concatArrays": [ "$$<YourFieldName>", "$$this" ] } } }, "in": { "$gte": [ { "$strLenCP": "$$this" }, <size of array>] } } } } }
Where <YourFieldName> is the Mongo Field Name whose value length needs to be calculated.
MongoDB nested array string field value greater than query >
Below is the MongoDB string field value length greater than the query.
Example
In the below query, we get records where the field exists and the field length is greater than 5 characters in size.
MongoDB nested Array field string value length less than query <
Below is the mongo Shell query for less than dates.
Query Pattern
Replace in the above query,
"in": { "$lte": [ { "$strLenCP": "$$this" }, <size of array>] }
MongoDB nested Array field string value length Equal to length =
Below is the mongo Shell query for equal to length query.
Query Pattern
Replace in the above query,
"in": { "$eq": [ { "$strLenCP": "$$this" }, <size of array>] }
Using Regex – MongoDB nested array string field value length query
For more details on this approach please visit:
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.
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!