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
Get array items inside a MongoDB document?
To get array items in a MongoDB document, use the dot (.) notation to access fields within array elements. This allows you to query documents based on values inside arrays and retrieve specific array items.
Syntax
db.collection.find({"arrayName.fieldName": "value"});
Sample Data
db.demo29.insertMany([
{
"StudentDetails": [
{"StudentName": "Chris", "StudentMarks": 58},
{"StudentName": "Bob", "StudentMarks": 69}
]
},
{
"StudentDetails": [
{"StudentName": "David", "StudentMarks": 97},
{"StudentName": "Carol", "StudentMarks": 96}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e15fcc08f2315c2efc48e6e"),
ObjectId("5e15fcd38f2315c2efc48e6f")
]
}
Display All Documents
db.demo29.find().pretty();
{
"_id": ObjectId("5e15fcc08f2315c2efc48e6e"),
"StudentDetails": [
{
"StudentName": "Chris",
"StudentMarks": 58
},
{
"StudentName": "Bob",
"StudentMarks": 69
}
]
}
{
"_id": ObjectId("5e15fcd38f2315c2efc48e6f"),
"StudentDetails": [
{
"StudentName": "David",
"StudentMarks": 97
},
{
"StudentName": "Carol",
"StudentMarks": 96
}
]
}
Query Array Items
Find documents containing a student named "David" ?
db.demo29.find({"StudentDetails.StudentName": "David"});
{
"_id": ObjectId("5e15fcd38f2315c2efc48e6f"),
"StudentDetails": [
{
"StudentName": "David",
"StudentMarks": 97
},
{
"StudentName": "Carol",
"StudentMarks": 96
}
]
}
Conclusion
Use dot notation to query array fields in MongoDB documents. The syntax arrayName.fieldName matches documents where any array element contains the specified field value.
Advertisements
