Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query MongoDB subdocument to print on one line?
To display subdocuments in one line, use $unwind along with aggregate(). Let us create a collection with documents −
> 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" }
Display all documents from a collection with the help of find() method −
> db.demo183.find().pretty();
This will produce the following output −
{
"_id" : "110",
"DueDate" : ISODate("2020-02-04T01:10:42Z"),
"ProductDetails" : [
{
"ProductName" : "Product-1",
"isAvailable" : true
},
{
"ProductName" : "Product-2",
"isAvailable" : false
}
]
}
Following is how to query subdocument and print on one line −
> 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 );
This will produce the following output −
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
Advertisements