MongoDB- Find a document with an array containing a specific value

Today in this article, we will see how to query MongoDB- Find document with array contains a specific value.

We will cover below a few specific scenarios like dealing with [] array type elements,

  • Get documents based on matching 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.

Today in this article, we will cover below aspects,

MongoDB – Find document by specified array value

Command

{ <field>: {<value> }

The below example shows an array filter where we get the list of documents where the value of an array element i.e books[] is equal to the value specified.

Example

{ books: "white"}

MongoDB – Find documents by an array length

Command

{ <array-field>: {$size :<size-specified> }

The below example shows an array filter where we get the list of documents based on array size i.e domain [] size is equal to the size specified.

Example

{ domain: { $size: 1} }

MongoDB – Find a document with an array by specifying multiple conditions

Command

{ <field>: {$gt :<size-specified> }

The below example shows an array filter where we get the list of documents where the value of any array element i.e domain [] is greater than 14.

{ domain: { $gt: 14 } }

The above query returns all the documents where an array field “domain” contains value 14.

MongoDB Find document with array contains a specific value

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.



Leave a Reply

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