Query MongoDB subdocument to print on one line?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 27-Mar-2020 12:32:08
Advertisements