Array Operators
The Array operators in the MongoDB return the result based on the Multiple conditions specified in the array using the array operators.
The Array Operators in the MongoDB are:
Array Operator | Description | Syntax |
---|---|---|
$all |
Returns the documents in the collection which have all the elements specified in the array. | { field: { $all: [<value1> , <value2>, ... ] } } |
$elemMatch |
Returns the documents that match all the conditions in the given array of conditions. | { field: { $elemMatch: { <query1>, <query2>, ... } } } |
$size |
Returns the documents that satisfy the given size mentioned in the query if the field contains an array of specified size. | { field: { $size: value } } |
Example of Using $all Operator
Let’s find out the Person whose Age is 23.
Query:
db.count_no.find( {"Age" :{$all : [23] } }, {_id:0} );
Output:
Explanation: In the above query, We have used the $all operator along with the Age and it should have all the values in the array and it should be of array type.
Example of Using $elemMatch Operator
Let’s first make some updates in our demo collection. Here we will Insert some data into the count_no database
Query:
db.count_no.insertOne( {"name" : "Harsha", "Age": 24,"Likes" : 2,"Colors":["Red","Green","Blue"] } );
Output:
Now, using the $elemMatch operator in MongoDB let’s match the Red colors from a set of Colors.
Query:
db.count_no.find( {"Colors": {$elemMatch: {$eq: "Red" } } },{_id: 0 } );
Output:
Explanation: The $elemMatch operator is used with the field Colors which is of type array. In the above query, it returns the documents that have the field Colors and if any of the values in the Colors field has “Red” in it.
MongoDB Query and Projection Operator
MongoDB query and projection operators allow users to control queries and results. Query operators help to filter data based on specific conditions. E.g., $eq,$and,$exists, etc.
Projection operators in MongoDB control which fields should be shown in the results. E.g., $project, $slice, $concat, etc.
In this article, we will learn about query and projection operators in MongoDB with detailed explanations and examples. Let’s start by learning the Query operators in MongoDB.