如何對MongoDB中的陣列項進行分組並統計價格相似的產品數量?


要對陣列項進行分組,請使用$group和$sort。讓我們建立一個帶有文件的集合,程式碼如下:

> db.demo566.insertOne(
... {
...
...    "ProductInformation" : [
...       {
...          "ProductName" : "Product-1",
...          "ProductPrice" :100
...       },
...       {
...          "ProductName" : "Product-2",
...          "ProductPrice" :1100
...       },
...       {
...          "ProductName" : "Product-3",
...          "ProductPrice" :100
...       },
...       {
...          "ProductName" : "Product-4",
...          "ProductPrice" :1100
...       },
...       {
...          "ProductName" : "Product-5",
...          "ProductPrice" :100
...       }
...    ]
...
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a")
}

在find()方法的幫助下顯示集合中的所有文件,程式碼如下:

> db.demo566.find();

這將產生以下輸出:

{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "ProductInformation" : [
   { "ProductName" : "Product-1", "ProductPrice" : 100 },
   { "ProductName" : "Product-2", "ProductPrice" : 1100 },
   { "ProductName" : "Product-3", "ProductPrice" : 100 },
   { "ProductName" : "Product-4", "ProductPrice" : 1100 },
   { "ProductName" : "Product-5", "ProductPrice" : 100 } 
] }

以下是用於對陣列項進行分組的查詢:

> db.demo566.aggregate([
... {
...    "$unwind": "$ProductInformation"
... },
... {
...    "$group": {
...       "_id": "$ProductInformation.ProductPrice",
...       "Value": { "$sum" : 1 }
...    }
... },
... { "$sort": { "_id" :1 } }
... ])

這將產生以下輸出:

{ "_id" : 100, "Value" : 3 }
{ "_id" : 1100, "Value" : 2 }

更新於: 2020-05-14

857 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.