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 database
To retrieve array values from a find query in MongoDB, use dot notation to access nested fields within array elements. This allows you to query specific properties of objects stored in arrays.
Syntax
db.collection.find({"arrayName.fieldName": "value"});
Sample Data
Let us create a collection with documents containing arrays of client details ?
db.demo38.insertMany([
{"ClientDetails": [{"ClientId": 101, "ClientName": "Chris"}]},
{"ClientDetails": [{"ClientId": 102, "ClientName": "David"}]},
{"ClientDetails": [{"ClientId": 103, "ClientName": "Mike"}]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e176abccfb11e5c34d898d9"),
ObjectId("5e176ac7cfb11e5c34d898da"),
ObjectId("5e176ad0cfb11e5c34d898db")
]
}
Display all documents from the collection ?
db.demo38.find();
{ "_id": ObjectId("5e176abccfb11e5c34d898d9"), "ClientDetails": [{"ClientId": 101, "ClientName": "Chris"}] }
{ "_id": ObjectId("5e176ac7cfb11e5c34d898da"), "ClientDetails": [{"ClientId": 102, "ClientName": "David"}] }
{ "_id": ObjectId("5e176ad0cfb11e5c34d898db"), "ClientDetails": [{"ClientId": 103, "ClientName": "Mike"}] }
Example: Query Array Values Using Dot Notation
Following is the query to retrieve documents where the ClientName is "David" ?
db.demo38.find({"ClientDetails.ClientName": "David"});
{ "_id": ObjectId("5e176ac7cfb11e5c34d898da"), "ClientDetails": [{"ClientId": 102, "ClientName": "David"}] }
Key Points
- Use
arrayName.fieldNamesyntax to query nested fields within arrays - MongoDB automatically searches all elements in the array for the specified condition
- The query returns the entire document when a match is found
Conclusion
Dot notation provides a simple way to query array elements in MongoDB. Use arrayName.fieldName to search for specific values within nested objects in arrays.
Advertisements
