MongoDB 查詢以計算陣列中每個元素的頻率


進行計數時,還可以使用 aggregate() 和 $sum。讓我們建立一個包含文件的集合 −

> db.demo184.insertOne({"Names":["Chris","David","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3999fb9e4f06af55199805")
}
> db.demo184.insertOne({"Names":["Chris","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399a0d9e4f06af55199806")
}
> db.demo184.insertOne({"Names":["Chris","Bob","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e399a209e4f06af55199807")
}

使用 find() 方法顯示某個集合中的所有文件 −

> db.demo184.find();

這會產生以下輸出 −

{ "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] }
{ "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] }
{ "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] }

以下是對每個元素進行計數的查詢 −

> db.demo184.aggregate([
...   { "$unwind" : "$Names" },
...   { "$group": { "_id": "$Names", "count": { "$sum": 1} } },
...   { "$group": {
...      "_id": null,
...         "counts": {
...            "$push": {
...               "k": "$_id",
...               "v": "$count"
...            }
...         }
...      } },
...      { "$replaceRoot": {
...         "newRoot": { "$arrayToObject": "$counts" }
...   } }
...])

這會產生以下輸出 −

{ "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }

更新於: 2020 年 3 月 27 日

750 次瀏覽

開啟你的 職業生涯

完成課程後獲取認證

開始
廣告
© . All rights reserved.