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
Retrieving array values from a find query in MongoDB?
To retrieve array values from a MongoDB find query, use dot notation to access array fields and their nested properties. This allows you to query specific elements within arrays and filter documents based on array content.
Syntax
db.collection.find({"arrayField.nestedProperty": "value"});
Sample Data
db.retrievingArrayDemo.insertMany([
{
"UserDetails": [
{ "UserName": "John", "UserAge": 23 }
],
"UserCountryName": "AUS",
"UserLoginDate": new ISODate(),
"UserMessage": "Hello"
},
{
"UserDetails": [
{ "UserName": "Sam", "UserAge": 24 }
],
"UserCountryName": "UK",
"UserLoginDate": new ISODate(),
"UserMessage": "Bye"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ce9718478f00858fb12e920"),
ObjectId("5ce9718478f00858fb12e921")
]
}
Example 1: Display All Documents
db.retrievingArrayDemo.find().pretty();
{
"_id" : ObjectId("5ce9718478f00858fb12e920"),
"UserDetails" : [
{
"UserName" : "John",
"UserAge" : 23
}
],
"UserCountryName" : "AUS",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"),
"UserMessage" : "Hello"
}
{
"_id" : ObjectId("5ce9718478f00858fb12e921"),
"UserDetails" : [
{
"UserName" : "Sam",
"UserAge" : 24
}
],
"UserCountryName" : "UK",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
"UserMessage" : "Bye"
}
Example 2: Query Array Values Using Dot Notation
Retrieve documents where UserCountryName is "UK" and UserDetails array contains a user named "Sam" :
db.retrievingArrayDemo.find({
"UserCountryName": "UK",
"UserDetails.UserName": "Sam"
}).pretty();
{
"_id" : ObjectId("5ce9718478f00858fb12e921"),
"UserDetails" : [
{
"UserName" : "Sam",
"UserAge" : 24
}
],
"UserCountryName" : "UK",
"UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"),
"UserMessage" : "Bye"
}
Key Points
- Use dot notation (
arrayField.property) to access nested properties within arrays - MongoDB automatically searches through all array elements for matching values
- Multiple conditions can be combined to filter documents precisely
Conclusion
Dot notation provides a simple way to query array values in MongoDB. Use "arrayField.nestedProperty" syntax to filter documents based on array content and retrieve specific data efficiently.
Advertisements
