查詢 MongoDB 子文件並輸出在一行?


若要在一行中顯示子文件,請在聚合() 中使用 $unwind。 讓我們建立一個包含文件的集合 -

> 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" }

藉助 find() 方法顯示集合中的所有文件 -

> db.demo183.find().pretty();

這將生成以下輸出 -

{
   "_id" : "110",
   "DueDate" : ISODate("2020-02-04T01:10:42Z"),
   "ProductDetails" : [
      {
         "ProductName" : "Product-1",
         "isAvailable" : true
      },
      {
         "ProductName" : "Product-2",
         "isAvailable" : false
      }
   ]
}

以下是查詢子文件並在同一行中列印的方法 -

> 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

更新於:2020-03-27

262 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.