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
Fetch records from a subdocument array wherein id begins from 234 in MongoDB
To fetch records from a subdocument array where id begins with specific digits like "234", use MongoDB's aggregation pipeline with $unwind, $match, and $regex operators. The $unwind deconstructs the array, $regex filters by pattern, and $group with $push reconstructs matching elements.
Syntax
db.collection.aggregate([
{ $match: { "_id": documentId } },
{ $unwind: "$arrayField" },
{ $match: { "arrayField.id": { $regex: /^pattern/ } } },
{ $group: { _id: "$_id", "result": { $push: "$arrayField" } } }
]);
Sample Data
db.demo556.insertOne({
_id: 101,
details: [
{ id: "234336", Name: "Chris" },
{ id: "123456", Name: "Bob" },
{ id: "234987", Name: "Carol" },
{ id: "989768", Name: "David" },
{ id: "234888", Name: "Sam" },
{ id: "847656", Name: "John" }
]
});
{ "acknowledged": true, "insertedId": 101 }
Example: Fetch Records with IDs Beginning "234"
Use aggregation pipeline to filter subdocuments where id starts with "234" ?
db.demo556.aggregate([
{ $match: { "_id": 101 } },
{ $unwind: "$details" },
{ $match: { "details.id": { $regex: /^234/ } } },
{ $group: { _id: "$_id", "Detail": { $push: "$details" } } }
]);
{
"_id": 101,
"Detail": [
{ "id": "234336", "Name": "Chris" },
{ "id": "234987", "Name": "Carol" },
{ "id": "234888", "Name": "Sam" }
]
}
How It Works
-
$match: { "_id": 101 }− Filters the specific document -
$unwind: "$details"− Deconstructs the details array into separate documents -
$match: { "details.id": { $regex: /^234/ } }− Filters elements where id starts with "234" -
$groupwith$push− Reconstructs matching elements into a new array
Conclusion
Use MongoDB aggregation pipeline with $unwind, $regex, and $group to filter subdocument arrays by pattern matching. The $regex: /^234/ pattern efficiently matches IDs beginning with "234".
Advertisements
