MongoDB中的“结构化”分组查询,以显示结果的新字段显示计数
为此,请在MongoDBIN聚合()中使用$组。的$由指定_id表达和为每个不同的分组组群输入文档,输出一个文档。首先让我们创建一个包含文档的集合-
> db.demo534.insertOne({_id:10,"ProductId":100,"ProductName":"Product-1"}); { "acknowledged" : true, "insertedId" : 10 } > db.demo534.insertOne({_id:11,"ProductId":100,"ProductName":"Product-2"}); { "acknowledged" : true, "insertedId" : 11 } > db.demo534.insertOne({_id:12,"ProductId":101,"ProductName":"Product-1"}); { "acknowledged" : true, "insertedId" : 12 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo534.find();
这将产生以下输出-
{ "_id" : 10, "ProductId" : 100, "ProductName" : "Product-1" } { "_id" : 11, "ProductId" : 100, "ProductName" : "Product-2" } { "_id" : 12, "ProductId" : 101, "ProductName" : "Product-1" }
以下是在MongoDB中实现结构化分组查询的查询-
> db.demo534.aggregate( ... { ... $group: ... { ... _id: ... { ... productName: "$ProductName", ... productId: "$ProductId" ... }, ... count: ... { ... $sum: 1 ... } ... }, ... }, ... { ... $group: ... { ... _id: "$_id.productId", ... itemCounts: ... { ... "$push": ... { ... productName: "$_id.productName", ... count: "$count" ... } ... } ... } ... })
这将产生以下输出-
{ "_id" : 101, "itemCounts" : [ { "productName" : "Product-1", "count" : 1 } ] } { "_id" : 100, "itemCounts" : [ { "productName" : "Product-2", "count" : 1 }, { "productName" : "Product-1", "count" : 1 } ] }