Home » Software Development » MongoDB » MongoDB Array Query Operators Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

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
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of