MongoDB-Query deeply nested array containing a specific value
Today in this article, we will see how to MongoDB-Query deeply nested array containing a specific value.
Today in this article, we will cover below aspects,
We will cover below a few specific scenarios like dealing with [] array type elements,
- Get documents based on matching nested array size i.e where array size is greater or less than of given specified size.
- Find the array that contains specific values only.
- Specify conditions for array elements.
Sample schema as below,
In the above example, we have two nested arrays Example Books [] and Category [].
MongoDB – Find document from Nested array element
Command
Nested 3 array pattern,
{ <array-field1>.<array-field2>.<array-field3>.<Field-Name>: {<value> }
The below example shows an array filter where we get the list of documents where the value of a nested array element i.e category [] is equal to the value specified.
{'Books.category.key': 'test2-1'}
Example
MongoDB – Find documents by nested array length
Command
{ <array-field1>.<array-field2: {$size :<size-specified> }
Example
The below example shows an array filter where we get the list of documents based on array size i.e category [] size is equal to the size specified.
{'Books.category': {$size:2}}
MongoDB – Find a document with a nested array by specifying multiple conditions
Example
MongoDB query array with fields that contains a given string,
{'Books.category.key': {$regex: '-'}}
Above query returns records where array element “Key” attribute has a value that matches or contains “-“.
References: MongoDB Naming Standards and Guidelines
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
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.