Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to query a document in MongoDB comparing fields from an array?
To query documents in MongoDB by comparing fields from an array, use comparison operators like $gt (greater than) and $lt (less than) with dot notation to access array elements.
Syntax
db.collection.find({
"arrayName.fieldName": {
$gt: value1,
$lt: value2
}
});
Sample Data
Let us create a collection with documents containing score arrays ?
db.demo147.insertMany([
{"Details": [{"Score": 45}, {"Score": 46}]},
{"Details": [{"Score": 65}, {"Score": 86}]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e32fa21fdf09dd6d08539be"),
ObjectId("5e32fa40fdf09dd6d08539bf")
]
}
Display all documents from the collection ?
db.demo147.find().pretty();
{
"_id": ObjectId("5e32fa21fdf09dd6d08539be"),
"Details": [
{
"Score": 45
},
{
"Score": 46
}
]
}
{
"_id": ObjectId("5e32fa40fdf09dd6d08539bf"),
"Details": [
{
"Score": 65
},
{
"Score": 86
}
]
}
Example: Find Documents with Scores Between 45 and 50
Query documents where any Score in the Details array is greater than 45 and less than 50 ?
db.demo147.find({
"Details.Score": {
$gt: 45,
$lt: 50
}
});
{
"_id": ObjectId("5e32fa21fdf09dd6d08539be"),
"Details": [
{"Score": 45},
{"Score": 46}
]
}
Key Points
- Use dot notation
"arrayName.fieldName"to access fields within array elements. - MongoDB checks all array elements − if any element matches the condition, the document is returned.
- Combine multiple operators like
$gt,$lt,$gte,$ltefor range queries.
Conclusion
Use dot notation with comparison operators to query array fields in MongoDB. The query matches documents where any array element satisfies the specified conditions, making it efficient for filtering based on nested field values.
Advertisements
