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 a specific object from array of objects inside specific MongoDB document?
To get a specific object from array of objects inside a MongoDB document, use the positional operator $ in the projection to return only the matched array element.
Syntax
db.collection.find(
{ "arrayField.subField": "matchValue" },
{ "_id": 0, "arrayField.$": 1 }
);
Sample Data
Let us create a collection with documents −
db.getASpecificObjectDemo.insertOne({
_id: 1,
"CustomerName": "Larry",
"CustomerDetails": {
"CustomerPurchaseDescription": [
{
"id": 100,
"ProductName": "Product-1",
"Amount": 10000
},
{
"id": 101,
"ProductName": "Product-2",
"Amount": 10500
},
{
"id": 102,
"ProductName": "Product-3",
"Amount": 10200
}
]
}
});
{ "acknowledged": true, "insertedId": 1 }
Display all documents from the collection −
db.getASpecificObjectDemo.find().pretty();
{
"_id": 1,
"CustomerName": "Larry",
"CustomerDetails": {
"CustomerPurchaseDescription": [
{
"id": 100,
"ProductName": "Product-1",
"Amount": 10000
},
{
"id": 101,
"ProductName": "Product-2",
"Amount": 10500
},
{
"id": 102,
"ProductName": "Product-3",
"Amount": 10200
}
]
}
}
Example
Get the specific object with id 101 from the array −
db.getASpecificObjectDemo.find(
{ _id: 1, "CustomerDetails.CustomerPurchaseDescription.id": 101 },
{ _id: 0, "CustomerDetails.CustomerPurchaseDescription.$": 1 }
);
{
"CustomerDetails": {
"CustomerPurchaseDescription": [
{
"id": 101,
"ProductName": "Product-2",
"Amount": 10500
}
]
}
}
Key Points
- The
$operator returns only the first matching element from the array. - Use dot notation to match nested array fields in the query condition.
- The projection field must match the same path as used in the query condition.
Conclusion
The positional operator $ efficiently retrieves specific objects from arrays by matching query conditions and projecting only the matched element. This approach is ideal when you need a single matching object rather than the entire array.
Advertisements
