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 get values greater than a specific value from an embedded list in MongoDB?
To get values greater than a specific value from an embedded list in MongoDB, use the $gt operator with dot notation to target fields within the embedded array. This will return entire documents that contain at least one array element matching the condition.
Syntax
db.collection.find({ "arrayField.field": { $gt: value } })
Sample Data
Let us create a collection with documents containing embedded arrays ?
db.demo317.insertMany([
{
"id": 101,
"details": [
{ "Score": 78, "Name": "Chris" },
{ "Score": 88, "Name": "David" }
]
},
{
"id": 102,
"details": [
{ "Score": 90, "Name": "Chris" },
{ "Score": 91, "Name": "David" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e50e69cf8647eb59e562060"),
ObjectId("5e50e6adf8647eb59e562061")
]
}
Display all documents from the collection ?
db.demo317.find();
{
"_id": ObjectId("5e50e69cf8647eb59e562060"),
"id": 101,
"details": [
{ "Score": 78, "Name": "Chris" },
{ "Score": 88, "Name": "David" }
]
}
{
"_id": ObjectId("5e50e6adf8647eb59e562061"),
"id": 102,
"details": [
{ "Score": 90, "Name": "Chris" },
{ "Score": 91, "Name": "David" }
]
}
Example: Find Scores Greater Than 89
To find documents with embedded Score values greater than 89 ?
db.demo317.find({ "details.Score": { $gt: 89 } });
{
"_id": ObjectId("5e50e6adf8647eb59e562061"),
"id": 102,
"details": [
{ "Score": 90, "Name": "Chris" },
{ "Score": 91, "Name": "David" }
]
}
Key Points
- Use dot notation (
"arrayField.field") to access fields within embedded arrays - The
$gtoperator returns documents where at least one array element satisfies the condition - The entire document is returned, not just the matching array elements
Conclusion
MongoDB's $gt operator with dot notation effectively queries embedded arrays. Use "arrayName.fieldName": { $gt: value } to find documents containing array elements that exceed the specified threshold value.
Advertisements
