MongoDB Query an Array

MongoDB is an open-source document, NoSQL database that stores the data in a document-oriented structure. With the help of MongoDB, we can handle large, complex, and unstructured data efficiently because MongoDB is widely used for Scalability and Flexibility.

In this article, we will learn about the Array Element and How to query array elements in MongoDB and perform various queries to get an exceptional understanding of Array elements in MongoDB.

Query an Array in MongoDB

MongoDB’s flexible structure makes it a popular choice for storing and managing diverse data. In MongoDB, data is stored in collections and collections have documents that support data types like strings, numbers, objects, and most important arrays.

Arrays in MongoDB allow the users to store data in an ordered form. Efficiently querying array elements is crucial for developers to extract meaningful information from the databases.

Prerequisites

Before moving forward make sure you are familiar with: 

Different Methods in MongoDB to Query Array Elements

MongoDB provides a variety of methods to access and query array elements within the documents.

Method Definition Syntax
Query using dot notation dot notation to access an element by its index in the array. db.collection.find({“arrayName.index”: “value”})
Query using $elemMatch $elemMatch operator matches documents that contain an array with at least one element that matches the specified query criteria. db.collection.find({ <arrayField>:{$elemMatch: {<query>}})
Query using $slice The $slice is a projection operator in MongoDB that limits the number of elements from an array to return in the results. db.collection.find( {}, {arrayName: { $slice: 5 }})
Unwinding Unwinding allows users in MongoDB to output a document for each element in the array. This makes it easier for the developers to run aggregation queries on the array data. db.collection.aggregate([{$unwind: “$arrayName”}])

Query an Array Elements in MongoDB Examples

To understand how we can query array elements in MongoDB let’s create a demo collection in MongoDB. The following collection is named blogPosts and has 3 fields- id, title, and comments.

In the collection, the comments field is an array that consists of user details. Each collection consists of two user details inside the comments array. We will query these comments array for better understanding.

Below are the data or records inserted into the document of blogPosts collections.

The above data or record is for Indian Cuisine and Bollywood

The above data or record is for Indian Festival and Cricket

The above data or record is for Yoga

Note: For better understanding, we have provided methods for users who use MongoDB Compass as well as users using Mongo Shell to perform the query. You can follow any one method whichever is suitable for you.

Query the Array Elements Using the Dot Notation Example

In the following example, We will see how we can query the array elements present in a collection via the dot notation in MongoDB. The find function is used along with the dot notation to fetch the required results.

Query Using the Mongo Shell:

db.blogPosts.find({ "comments.user": "AaravSingh" });

Output:

Output on MongoShell

Explanation: The following query searches for documents in the blogPost collection for at least one comment with the user field “AaravSingh”. The db.blogPosts specifies the collection name, and the find() function is used to retrieve the documents from the collection based on the query criteria provided by the user. 

{ “comments.user”: “AaravSingh” } is the main query criteria, it looks for documents where the array named “comments” contains at least one element with a user whose name is “AaravSingh“.

Query Using the MongoDB Compass:

 { "comments.user": "AaravSingh" }

Output:

Output on MongoDBCompass

Explanation: If we are executing the query in the mongoDB compass then we don’t have to specify the collection name and use the find function. We can directly place the query in the query execution tab. 

{ “comments.user”: “AaravSingh” } query will search the comments array and find all the users with the specified name.

Query Array Elements Using $elemMatch Operator Example

In the following example, We will learn how we can query the array elements present in a collection via the dot $elemMatch Operator in MongoDB.

Query Using the Mongo Shell:

db.blogPosts.find({ comments: { $elemMatch: { user: "AnanyaMishra" } } });

Output:

Output on MongoShell

Explanation: In the following query, We have fetched the documents from the blogPost collection where there is at least one comment with the user field “AnanyaMishra“. The db.blogPosts specifies the name of the collection, find() function is used to fetch the documents from the collection based on the condition provided by the user. 

{ comments: { $elemMatch: { user: “AnanyaMishra” } } } is the main query condition. It used the $elemMatch operator to match the documents where at least one element in the “comments” array has the user field as “AnanyaMishra”.

Query Using the MongoDB Compass:

{ comments: { $elemMatch: { user: "AnanyaMishra" } } }

Output:

Output on MongoDBCompass

Explanation: If we are executing the query in the MongoDB Compass then we don’t have to use the find function and there is no need to specify the name of the collection. It is already included by default, we will just have to enter the query and the result will be fetched out. 

{ comments: { $elemMatch: { user: “AnanyaMishra” } } } query uses the $elemMatch operator to search the array named comments and find out all the users whose name matches with the specified name “AnanyaMishra”.

Query Array Element using $slice Operator Example 

In the following example, we will see how we can filter our result set using the $slice operator in MongoDB.

Query Using the Mongo Shell:

db.blogPosts.find({}, { title: 1, comments: { $slice: 2 } });

Output:

Output on MongoShell

Explanation: The following query retrieves documents from the blogPosts collection which only includes the title field and first two elements from the comments and the rest of the comments are filtered out using the $slice operator. The db.blogPosts specifies the name of the collection, find() function is used to retrieve the documents from the collection based on the specified query criteria provided by the user. 

{ title: 1, comments: { $slice: 2 } }, this is the main criteria part for the query where documents are included with the title field and only 2 elements from the comment array are included in the result set.

Query Using the MongoDB Compass:

{}, { title: 1, comments: { $slice: 2 } }

Output:

Output on MongoDBCompass

Explanation: If we are executing the query in the MongoDB Compass then we don’t have to use the find function and there is no need to specify the name of the collection. We will just have to enter our query and the result will be fetched out.

{ title: 1, comments: { $slice: 2 } } query uses the $slice operator to filter out the result set and only include two values in the final result set which is returned to the user.

Query Array Elements Using $all Operator Example

In the following example, we will learn how we can query the array elements in MongoDB via the $all operator. The $all operator is used to fetch all the data that matches the mentioned condition.

Query Using the Mongo Shell:

db.blogPosts.find({
comments: {
$all: [
{ $elemMatch: { user: "AmitPatel" } },
{ $elemMatch: { user: "SanyaSingh" } }
]
}
});

Output:

Output on MongoShell

Explanation: The following query is used to fetch all the documents from the blogPost collection where the comments array contains user names “AmitPatel” and “SanyaSingh“. db.blogPosts specifies the name of the collection, find() function is used to fetch the documents from the collection based on the condition provided by the user. 

comments: {$all: [ { $elemMatch: { user: “AmitPatel” } }, { $elemMatch: { user: “SanyaSingh” } }]} is the main query condition. It uses the $all operator to fetch all the documents in which the comments array contains elements with the conditions provided by the user.

Query Using the MongoDB Compass:

{
comments: {
$all: [
{ $elemMatch: { user: "AmitPatel" } },
{ $elemMatch: { user: "SanyaSingh" } }
]
}
}

Output:

Output on MongoCompass

Explanation: If we are executing the query in the MongoDB Compass then we don’t have to use the find function and there is no need to specify the name of the collection. We will just have to enter our query and the result will be fetched out. 

{comments: {$all: [ { $elemMatch: { user: “AmitPatel” } }, { $elemMatch: { user: “SanyaSingh” } } ] } } the following query searches the comments array in the document and extracts all the occurrences of the user mentioned in the query with the help of $all operator.

Query Array Element Using $in Operator Example 

In the following example, we will learn how we can query array elements using the $in operator.

Query Using the Mongo Shell:

db.blogPosts.find({ comments: { $elemMatch: { user: { $in: ["DeepakVerma", "TanviMalhotra"] } } } });

Output:

Output on MongoShell

Explanation: The following query is used to search the documents from the blogPosts collection where the comments array contains at least one element with the user field which matches to “Deepakverma” and “TanviMalhotra“. db.blogPosts specifies the name of the collection, find() function is used to retrieve the documents from the collection based on the specified query criteria provided by the user.

 { comments: { $elemMatch: { user: { $in: [“DeepakVerma”, “TanviMalhotra”] } } } } in this part of the query the main criteria are specified. It uses the $in operator to match documents where the user field of at least one comment is either “DeepakVerma” or “TanviMalhotra“.

Query Using the MongoDB Compass:

{ comments: { $elemMatch: { user: { $in: ["DeepakVerma", "TanviMalhotra"] } } } }

Output:

Output on MongoDBCompass

Explanation: We don’t have to mention the name of the document and use the find function in the query to extract the results in MongoDB Compass, these two things are included in the MongoDB Compass by default. We will just have to enter our query and the result will be fetched out. 

{ comments: { $elemMatch: { user: { $in: [“DeepakVerma”, “TanviMalhotra”] } } } } query uses the $in operator to match documents where comments array has one user whose name is either “DeepakVerma” or “TanviMalhotra”.

Conclusion

In this article, We have learned how to query array elements in MongoDB. We have learned the use cases of various operators like $lemeMatch, $slice, and many more with step-by-step explanations. It is important to note that we must use the operators carefully according to our needs the wrong use of operators can provide unwanted results in many cases.

Frequently Asked Questions of Querying on Array Elements

Is it possible to query arrays in nested documents?

Yes, MongoDB allows you to query arrays within the nested documents as well.

How can we improve the performance of our array queries?

Ensure that your databases are properly indexed for optimal performance of the queries.

How to Unwind an array in MongoDB?

In the MongoDB shell, you can unwind an array using the aggregation pipeline stage $unwind. Eg- db.collectionName.aggregate([  { $unwind: “$arrayFieldName” } ])

Can we limit the number of elements returned from an array in MongoDB?

Yes, you can limit the number of elements in the result using the $slice operator.

Can we combine array queries with other filters?

Absolutely, MongoDB allows users to combine array queries with various document level filters.