Chapter Introduction
In this chapter, we will introduce the array field matching operators in MongoDB's JSON documents.
Array Query Operators Supported by MongoDB
Operator | Description |
---|---|
$all | Matches the entire array value in the query condition |
$elemMatch | For array fields, if any value matches all the conditions set by $elemMatch, the condition is met |
$size | Matches the array size |
$all
{ tags: { $all: [ "ssl" , "security" ] } }
Equivalent to
{ $and: [ { tags: "ssl" }, { tags: "security" } ] }
The tags
field is an array value, and the tags
array simultaneously contains the values ssl
and security
.
$elemMatch
Test Data
The scores
collection data is as follows:
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
Example:
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
Returned Data:
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
Explanation:
- If any value in the
results
array is greater than or equal to 80 and less than 85, the document is successfully matched.
$size
Matches the array size
db.collection.find( { field: { $size: 2 } } );
Explanation:
- The
field
field is an array value, and if the array size is equal to 2, the document is successfully matched.