如何利用 MongoDB 巢狀 $group 和 $sum 獲得具有相同 ProductID 的庫存數量?
MongoDB 中的 $group 用於按指定 _id 表示式對輸入文件進行分組。我們建立一個包含文件的集合 −
> db.demo466.insertOne(
... {
...
... "ProductPrice" :150,
... "ProductQuantity" : 1,
... "ProductName" : "Product-1",
... "ActualAmount" :110,
... "ProductProfit" : 40,
... "ProductId" : 1
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477cb0f3fa88e2279066")
}
>
> db.demo466.insertOne(
... {
...
... "ProductPrice" :150,
... "ProductQuantity" : 1,
... "ProductName" : "Product-1",
... "ActualAmount" :110,
... "ProductProfit" : 40,
... "ProductId" : 2
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477db0f3fa88e2279067")
}
> db.demo466.insertOne(
... {
...
... "ProductPrice" :170,
... "ProductQuantity" : 2,
... "ProductName" : "Product-2",
... "ActualAmount" :130,
... "ProductProfit" : 50,
... "ProductId" : 3
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e80477eb0f3fa88e2279068")
}使用 find() 方法顯示集合中的所有文件 −
> db.demo466.find();
將生成以下輸出 −
{ "_id" : ObjectId("5e80477cb0f3fa88e2279066"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 1 }
{ "_id" : ObjectId("5e80477db0f3fa88e2279067"), "ProductPrice" : 150, "ProductQuantity" : 1,
"ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 2 }
{ "_id" : ObjectId("5e80477eb0f3fa88e2279068"), "ProductPrice" : 170, "ProductQuantity" : 2,
"ProductName" : "Product-2", "ActualAmount" : 130, "ProductProfit" : 50, "ProductId" : 3 }以下是 MongoDB 中使用巢狀 $group 和 $sum 的查詢 −
> db.demo466.aggregate([
... {
... '$group': {
... '_id': {
... 'ProductName': '$ProductName',
... },
... 'ActualAmount': {'$sum': '$ActualAmount'},
... 'ProductQuantity': {'$sum': '$ProductQuantity'},
... 'ProductId': {'$addToSet': '$ProductId'},
... },
... },
... {
... '$project': {
... 'ProductQuantity': true,
... 'ActualAmount': true,
... 'NumberOfProductInStock': {'$size': '$ProductId'}
... }
... }])將生成以下輸出 −
{ "_id" : { "ProductName" : "Product-2" }, "ActualAmount" : 130, "ProductQuantity" : 2,
"NumberOfProductInStock" : 1 }
{ "_id" : { "ProductName" : "Product-1" }, "ActualAmount" : 220, "ProductQuantity" : 2,
"NumberOfProductInStock" : 2 }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP