MongoDB查询在一行中显示子文档
要在一行中显示子文档,请使用$unwind和aggregate()。让我们创建一个包含文档的集合-
> 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