如何聚合以使用字段数组中的相同字符串求平均值

时间:2019-03-28 02:28:53

标签: aggregation-framework

我在这里有问题。这是我在mongodb中的字段:

{"_id" : ObjectId("5c9c25b7ae9b9d188f088492"),
    "Title" : "PENERAPAN_DATA MINING PADA PENJUALAN MENGGUNAKAN METODE CLUSTERING STUDY KASUS PT",
    "Author" : "sutrisno",
    "Keywords" : [ 

        {
            "keywordName" : "mining",
            "keywordSkor" : 0.0119760479041916
        }, 
        {
            "keywordName" : "tampil",
            "keywordSkor" : 0.0119760479041916
        }, 
        {
            "keywordName" : "data",
            "keywordSkor" : 0.0114316820903647
        },  

    ],
    "Creator" : "sutrisno",
}

"_id" : ObjectId("5c9c28f8ae9b9d1e2ee4e158"),
    "Title" : "Jurnal Komputer dan Informatika (KOMPUTA)",
    "Author" : "Farid Fansuri",
    "Keywords" : [ 
        {
            "keywordName" : "data",
            "keywordSkor" : 0.0869158878504672
        }, 
        {
            "keywordName" : "mining",
            "keywordSkor" : 0.0308411214953271
        }, 

如何获取具有相同字符串的字段Keywords的平均值 数据挖掘

"Keywords" : [
    {
        "keywordName" : "mining",
        "keywordSkor" : 0.0308411214953271
    }, 
    {
        "keywordName" : "data",
        "keywordSkor" : 0.0119760479041916
    }, 
     {
        "keywordName" : "tampil",
        "keywordSkor" : 0.0119760479041916
    },
]

1 个答案:

答案 0 :(得分:0)

使用聚合框架非常容易实现:

db.collection.aggregate([
  {
    $unwind: "$Keywords"
  },
  {
    $group: {
      _id: "$Keywords.keywordName",
      avg: {
        $avg: "$Keywords.keywordSkor"
      }
    }
  }
])

将输出:

[
  {
    "_id": "tampil",
    "avg": 0.0119760479041916
  },
  {
    "_id": "data",
    "avg": 0.04917378497041595
  },
  {
    "_id": "mining",
    "avg": 0.02140858469975935
  }
]