MongoDB is a widely used NoSQL database that provides support for arrays within documents.
Arrays in MongoDB are collections of values that can be of any data type, such as strings, integers, objects, or other arrays. As arrays can have multiple elements, querying arrays is a little different from querying regular fields in MongoDB. MongoDB provides several array operators that help in querying arrays efficiently. In this article, we will explore three of these array operators: $all, $elemMatch, and $size.
$all query operator
The $all operator matches arrays that contain all elements specified in the query. It is similar to the logical AND operator, where all the conditions must be satisfied for a match. The syntax of the $all operator is as follows:
{ field: { $all: [value1, value2, ..] } }
Let's consider an example to better understand the $all operator. Suppose we have a collection named users that contains documents with an array field languages that lists the languages known by each user.
{
"_id" : ObjectId("615b75a2f52414b09c2f0b0f"),
"name" : "John",
"languages" : [ "English", "Spanish", "French" ]
}
{
"_id" : ObjectId("615b75a2f52414b09c2f0b10"),
"name" : "Maria",
"languages" : [ "English", "Spanish", "Portuguese" ]
}We can use the $all operator to find all users who know both English and French by executing the following query:
db.users.find({ languages: { $all: ["English", "French"] } })
This query will return all the documents where the "languages" field contains both "English" and "French" elements.
{
"_id" : ObjectId("615b75a2f52414b09c2f0b0f"),
"name" : "John",
"languages" : [ "English", "Spanish", "French" ]
}As you can see, the query returns only one document where the "languages" array field contains all of the specified languages. The other document with the name "Maria" is not returned because she doesn't know "French".
$elemMatch operator
The $elemMatch operator selects documents if the element in the array field matches all the specified $elemMatch conditions. The syntax of the $elemMatch operator is as follows:
{ field: { $elemMatch: { expression } } }
The $elemMatch operator is useful when we want to specify more than one condition for a single element in an array. Let's consider an example to understand it better with more extended users collection.
db.users.insertMany([
{
name: "John",
age: 35,
languages: [
{ name: "English", experience: 7 },
{ name: "Spanish", experience: 3 },
{ name: "German", experience: 2 }
]
},
{
name: "Jane",
age: 28,
languages: [
{ name: "English", experience: 5 },
{ name: "French", experience: 4 }
]}
])Now we want to find all users who know "English" and have been speaking it for more than 5 years.
We can use the $elemMatch operator to execute the following query:
db.users.find({ languages: { $elemMatch: { name: "English", experience: { $gt: 5 } } } })
This query will return the document where the "name" field contains an element that matches both conditions. And that is John again!
$size query operator
The $size operator is used to query the number of elements in an array. The syntax of the $size operator is as follows:
{ field: { $size: value } }
Let's consider an example. Suppose we have a collection named books that contains documents with an array field authors that lists the authors of each book.
db.books.insertMany([
{
title: "Clean Code",
authors: ["Robert C. Martin"]
},
{
title: "Code Complete",
authors: ["Steve McConnell"]
},
{
title: "Cracking the Coding Interview",
authors: ["Gayle Laakmann McDowell"]
},
{
title: "Head First Design Patterns",
authors: ["Eric Freeman", "Elisabeth Robson", "Bert Bates", "Kathy Sierra"]
}
])We can use the $size operator to find all the books with more than three authors by executing the following query:
db.books.find({ authors: { $size: { $gt: 3 } } })
The $gt operator is used to specify that the size should be greater than 3.
This query will return only one document, which is the book "Head First Design Patterns", as it has four authors.
Conclusion
To sum up, in this topic we've covered several useful array operators of MongoDB that help us to query arrays efficiently:
the
$alloperator is used to match arrays that contain all elements specified in the query.the
$elemMatchoperator is used to select documents if the element in the array field matches all the specified$elemMatchconditions.the
$sizeoperator is used to query the number of elements in an array.
Now, it is high time to practice to master your new skills!