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
Query to retrieve multiple items in an array in MongoDB?
To retrieve multiple items in an array in MongoDB, use the aggregation framework with $unwind, $match, and $group operators to filter and reconstruct array elements based on specific criteria.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": { $in: [values] } } },
{ $group: { "_id": "$_id", "arrayField": { $push: "$arrayField" } } }
]);
Sample Data
db.retrieveMultipleDemo.insertOne({
"UserDetails": [
{ "_id": "101", "UserName": "John", "UserAge": 23 },
{ "_id": "102", "UserName": "Carol", "UserAge": 21 },
{ "_id": "103", "UserName": "David", "UserAge": 23 },
{ "_id": "104", "UserName": "Sam", "UserAge": 25 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd40c85edc6604c74817cf0")
}
Display All Documents
db.retrieveMultipleDemo.find().pretty();
{
"_id": ObjectId("5cd40c85edc6604c74817cf0"),
"UserDetails": [
{
"_id": "101",
"UserName": "John",
"UserAge": 23
},
{
"_id": "102",
"UserName": "Carol",
"UserAge": 21
},
{
"_id": "103",
"UserName": "David",
"UserAge": 23
},
{
"_id": "104",
"UserName": "Sam",
"UserAge": 25
}
]
}
Retrieve Multiple Items with Age Filter
Query to retrieve users with age 23 ?
db.retrieveMultipleDemo.aggregate([
{ $unwind: "$UserDetails" },
{ $match: { "UserDetails.UserAge": 23 } },
{ $group: { "_id": "$_id", "UserDetails": { $push: "$UserDetails" } } },
{ $project: { "_id": 0, "UserDetails": 1 } }
]);
{
"UserDetails": [
{ "_id": "101", "UserName": "John", "UserAge": 23 },
{ "_id": "103", "UserName": "David", "UserAge": 23 }
]
}
How It Works
-
$unwind− Deconstructs the array into separate documents -
$match− Filters documents based on array element criteria -
$group− Reconstructs the array with matching elements only -
$project− Shapes the final output format
Conclusion
Use MongoDB's aggregation pipeline to retrieve multiple filtered items from arrays. The combination of $unwind, $match, and $group provides powerful array filtering capabilities.
Advertisements
