MongoDB provides array operators to perform different queries on the arrays. There are three array operators:
$all
$size
$elemMatch
Let's perform different logical operators on the following database, named educative
, with a collection named courses
.
use educative //selecting our databasedb.courses.find({}) //showing all the documents of "courses"[{ _id: 10, course_name: 'python', hours: [10,14,20] },{ _id: 11, course_name: 'C++', hours: [10,15] },{ _id: 12, course_name: 'java', hours: [10,11,12] }]
{<field>:{$all: [ <value1> , <value2> ... ]}}
An example of the $all
operator is given below:
//querydb.courses.find({"hours": { $all: [10, 11]}}).pretty()//output[ { _id: 12, course_name: 'java', hours: [ 10, 11, 12 ] } ]
As we can see, the $all
operator returns only those hours
values that have both values 10 and 11.
Note: The
$all
operator is equivalent to an$and
operation of the specified values.
$size
operatorThis operator is used to find the documents with an array field whose size equals the specified size in a query clause.
Here's the syntax of the $size
operator:
{<field>:{$size: value}}
An example of the $size
operator is given below:
//querydb.courses.find({ "hours": { $size: 3}}).pretty()//output[{ _id: 10, course_name: 'python', hours: [ 10, 14, 20 ] },{ _id: 12, course_name: 'java', hours: [ 10, 11, 12 ] }]
As we can see, the $size
operator returns only those hours
values that have three elements.
$elemMatch
operatorThe $elemMatch
operator matches documents with an array field with at least one element that satisfies all the specified query criteria.
Here's the syntax of $elemMatch
operator:
{<field>:{$elemMatch:{<query1>, <query2>, ...}}}
An example of the $elemMatch
operator is given below:
//querydb.courses.find({ "hours": { $elemMatch: {$gte: 11, $lt: 15}}}).pretty()//output[{ _id: 10, course_name: 'python', hours: [ 10, 14, 20 ] },{ _id: 12, course_name: 'java', hours: [ 10, 11, 12 ] }]
As we can see, the $elemMatch
query in the example returns only those hours
values that are greater than or equal to 11 and less than 15.
You can run all the aforementioned MongoDB queries in the terminal below:
Free Resources