MongoDB Query for documents array size is greater than

MongoDB Query for documents array size is greater than

Today in this article we will see how to perform MongoDB – Query for documents array size greater than 1 or more.

Recently I was trying to find all the records where the array field has more than 1 entry.

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.

Today in this article, we will cover below aspects,

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

{
  "_id": "617f1b826cbcd5cf388e44f7",
  "Ssn": {
    "$binary": "AQN8wobDt3M8SsOPwrjDsHNVw5Ymwo3DlQJ1AQpYwrhyw6oIwp/CgAzCpCHDqcKBwrDCjTo+w4/CsMO0wozDmmfCuxE7w4tywofDoR/DhMOgw6HDhsKZwoRLwovCu8KDXQTCncKbL11nwpRQBMKeTcKLFlXCvwYxwrxUwoo=",
    "$type": "0"
  },
  "City": "NY",
  "Country": "USA",
  "States": "NY",
  "Zip": "12345",
  "order":  [ "name1",  "name2", "name3" ],
  "Name": "John"
}

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.

Approach I – MongoDB Query using the not-equal operator

Command

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

Example

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

The above query confirms if the array element has at least 1 or more records.

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

Approach II – MongoDB Query for documents array size is greater than 0 or 1 or 2

Query – MongoDB array documents with a count greater than1

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

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

query for documents where array size is greater than

Get MongoDB array documents with a count greater than 2

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

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

query for documents where array size is greater than

References:

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 *