Find MongoDB records where array field is not empty

Find MongoDB records where array field is not empty $ne

Today in this article we will see how to Find MongoDB records where array field is not empty or empty.

Recently I was trying to find all the records where the array field has more than documents. After the initial trivial, I found there is no direct query but was able to find a query that helped me address this requirement easily.

Below is a sample JSON where array order is defined as an array type.

Array order has 1 to 3 items in the collection.

We will build a query to find all the items where the array size is greater than 1.

Find MongoDB records where array field is not empty using $ne

Query

{<array field>: {$type:'array', $ne: [] }}

What is $ne

$ne is a comparison operator which lets you select the documents where the value of the field is not equal to the specified value.

Example

{order: {$type: 'array', $ne: []}}

The above query verifies for the array “order” field is not empty.

The above query also means to return all the MongoDB documents where the array has at least 1 element existing.

In our above example, The below query gives us results for array size 1 or 2 or more as below,

Find MongoDB records where array field is not empty $ne

Find MongoDB records where array field is empty using $eq

Query

{<array field>: {$type:'array', $eq: [] }}

What is $eq

$eq is a comparison operator which lets you select the documents where the value of the field is equal to the specified value.

Example

{order: {$type: 'array', $eq: []}}

Alternatively, you can also use the below query to find all the documents where the array field is not empty.

{'order.0': {$exists: true}}

The above query will return all the records where the array size is greater than or equal to 1

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.



Leave a Reply

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