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 items from an object array in MongoDB?
To get items from an object array in MongoDB, use the aggregation pipeline with $unwind to flatten arrays, $match to filter specific documents, and $group to collect the desired items.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": { $in: ["value1", "value2"] } } },
{ $group: { _id: null, result: { $addToSet: "$arrayField.targetField" } } }
]);
Sample Data
db.demo459.insertOne({
"_id": 1,
"Information": [
{
"Name": "Chris",
"_id": ObjectId(),
"details": ["HR"]
},
{
"Name": "David",
"_id": ObjectId(),
"details": ["Developer"]
},
{
"Name": "Bob",
"_id": ObjectId(),
"details": ["Account"]
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Verify Sample Data
db.demo459.find();
{
"_id": 1,
"Information": [
{ "Name": "Chris", "_id": ObjectId("5e7ef4a7dbcb9adb296c95c9"), "details": ["HR"] },
{ "Name": "David", "_id": ObjectId("5e7ef4a7dbcb9adb296c95ca"), "details": ["Developer"] },
{ "Name": "Bob", "_id": ObjectId("5e7ef4a7dbcb9adb296c95cb"), "details": ["Account"] }
]
}
Example: Extract Details for Chris and Bob
db.demo459.aggregate([
{ $unwind: "$Information" },
{ $unwind: "$Information.details" },
{ $match: { "Information.Name": { $in: ["Chris", "Bob"] } } },
{ $group: { _id: null, detailList: { $addToSet: "$Information.details" } } }
]);
{ "_id": null, "detailList": ["Account", "HR"] }
How It Works
-
$unwind: "$Information"− Flattens the Information array into separate documents -
$unwind: "$Information.details"− Flattens the nested details array -
$match− Filters documents where Name is either "Chris" or "Bob" -
$group− Collects unique detail values using$addToSet
Conclusion
Use MongoDB's aggregation pipeline with $unwind, $match, and $group to extract specific items from object arrays. This approach efficiently filters and collects data from nested array structures.
Advertisements
