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 MongoDB subdocument to print on one line?
To display subdocuments in one line format, use $unwind along with aggregate() to flatten array elements, then iterate through results with a custom function.
Syntax
db.collection.aggregate([
{ $match: { "field": "value" } },
{ $unwind: "$arrayField" }
]).forEach(function(doc) {
print(doc.field1 + ", " + doc.arrayField.subfield + ", " + doc.arrayField.subfield2);
});
Sample Data
db.demo183.insertOne({
"_id": "110",
"DueDate": ISODate("2020-02-04T01:10:42.000Z"),
"ProductDetails": [
{
"ProductName": "Product-1",
"isAvailable": true
},
{
"ProductName": "Product-2",
"isAvailable": false
}
]
});
{ "acknowledged": true, "insertedId": "110" }
Example: Query Subdocuments in One Line
Create a custom function to format output and use $unwind to flatten the array ?
var productdata = function (d) {
print(d.DueDate + ", " + d.ProductDetails.ProductName + ", " + d.ProductDetails.isAvailable);
}
var iterator = db.demo183.aggregate([
{ $match: { _id: "110" } },
{ $unwind: '$ProductDetails' }
]);
iterator.forEach(productdata);
Tue Feb 04 2020 06:40:42 GMT+0530 (India Standard Time), Product-1, true Tue Feb 04 2020 06:40:42 GMT+0530 (India Standard Time), Product-2, false
How It Works
-
$unwindcreates separate documents for each array element -
$matchfilters documents by specific criteria -
forEach()iterates through results and applies custom formatting function - Each subdocument is printed on a single line with comma-separated values
Conclusion
Use $unwind in aggregation pipeline to flatten subdocument arrays, then apply forEach() with a custom function to display each subdocument on one formatted line.
Advertisements
