MongoDB

MongoDB Array Query Operators Example

Hello readers, in this tutorial, we will see the different array query operators in the Mongo database. Let’s study in brief the different ways in which these operators can be used.

1. Introduction

If you have installed the MongoDB application on Windows or Ubuntu operating system and you wish to learn the Array Query operators, then follow the below steps. It is very simple to use this feature, but before moving further let’s take a look at MongoDB and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.2 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

2. MongoDB Array Query Operators Example

In this MongoDB tutorial, we will learn how to handle the different array query operators provided by the Mongo database. But before moving further will the tutorial, we will need to create the sample collection. The following script is used to create a database called warehouse with collections as: inventory, survey, and color. Open the Mongo terminal and execute the script.

> use warehouse

> db.inventory.insertMany( [
	{ _id: 101, code: "xyz", tags: [ "school", "book", "bag", "headphone", "appliance" ], qty: [{ size: "S", num: 10, color: "blue" }, { size: "M", num: 45, color: "blue" }, { size: "L", num: 100, color: "green" }] }, 
	{ _id: 102, code: "abc", tags: [ "appliance", "school", "book" ], qty: [{ size: "6", num: 100, color: "green" }, { size: "6", num: 50, color: "blue" }, { size: "8", num: 100, color: "brown" }] }, 
	{ _id: 103, code: "efg", tags: [ "school", "book" ], qty: [{ size: "S", num: 10, color: "blue" }, { size: "M", num: 100, color: "blue" }, { size: "L", num: 100, color: "green" }] }, 
	{ _id: 104, code: "ijk", tags: [ "electronics", "school" ], qty: [{ size: "M", num: 100, color: "green" }] }
] );

> db.survey.insertMany( [
	{ _id: 111, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] },
	{ _id: 112, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] },
	{ _id: 113, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
] );

> db.color.insertMany( [
	{ _id: 121, field: [ "red" , "green" ] },
	{ _id: 122, field: [ "fruit" ] },
	{ _id: 123, field: [ "orange" , "lemon", "grapefruit" ] },
	{ _id: 124, field: [ "apple" , "lime" ] }
] );

If everything goes well, the database and the collections will be shown in the Mongo Workbench.

Fig. 1: Database & Collection Creation
Fig. 1: Database & Collection Creation

2.1 $all Operator

In Mongo database, the $all operator is used to retrieve the documents of a collection that matches the values specified in an array. Here is what the query syntax will look like.

Syntax

> db.collection_name.find( {<Field_name> : {$all : [<Value1>, <Value2>, <Value3>]}} )

where:

  • Field_name is the attribute name on which the document is retrieved
  • Value1 to ‘n’ are the values for which the particular documents are retrieved from a collection

Let’s understand this with the help of an example.

> db.inventory.find( { tags: { $all: [ "appliance", "school", "book" ] } } )

This command will only fetch those documents from the inventory collection where the value of the tags field matches the criteria array i.e. appliance, school, and book.

Fig. 2: $all operation
Fig. 2: $all operation

Do remember, if the values specified in the criteria array are not present in the document, then the find() method will not print any output.

Fig. 3: No documents retrieved
Fig. 3: No documents retrieved

2.2 $eleMatch Operator

In Mongo database, the $eleMatch operator is used to retrieve the documents of a collection that contain an array field with at least one element that matches all the query criteria. Here is what the query syntax will look like.

Syntax

> db.collection_name.find( {<Field_name> : {$eleMatch : [<Query1>, <Query2>, <Query3>]}} )

where:

  • Field_name is the attribute name on which the document is retrieved
  • Query1 to ‘n’ are the predicates on which a document is retrieved from the collection

Let’s understand this with the help of an example.

> db.survey.find( { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } } )

This command matches only those documents from the survey collection where the results array has at least one element with products equal to ‘xyz’ and score equal to ‘8’.

Fig. 4: $eleMatch operator
Fig. 4: $eleMatch operator

Do note, if developers specify a single query condition, then the $elemMatch expression is not necessary. For e.g. consider a case where the $eleMatch specifies only a single predicate i.e. { product: "xyz" }.

Fig. 5: $eleMatch operator with a single predicate
Fig. 5: $eleMatch operator with a single predicate

2.3 $size Operator

In Mongo database, the $size operator is used to retrieve those documents from the collection that matches an array with the provided number of elements. This operator cannot be used to find a range of sizes. Here is what the query syntax will look like.

Syntax

> db.collection_name.find( {<Field_name> : {$size : <no_of_elements>}} )

where:

  • Field_name is the attribute name on which the document is retrieved

Let’s understand this with the help of an example.

> db.color.find( { field: { $size: 2 } } )

This command returns all documents where the field is an array of 2 elements. Thus, the above expression will return { field: [ red, green ] } and { field: [ apple, lime ] } values but not { field: fruit } or { field: [ orange, lemon, grapefruit ] }.

Fig. 6: $size operator
Fig. 6: $size operator

Do note, the find() method used in above expressions displays the documents in a non-structured pattern. If developers want to display the output in a structured pattern, they can use the pretty() method.

That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the different Array Query operators of the Mongo database. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of the Array Query operators in the Mongo database.

Download
You can download the full source code of this example here: MongoDbArrayQueryOperatorsEx

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button