通过在mongo中使用两个集合来分组

时间:2018-03-30 22:21:40

标签: mongodb join group-by average

I have two following mongodb collections:

fact:
{ 
    "_id" : ObjectId("5ab70427fc08b4855d3c4ea2"), 
    "game_id" : NumberInt(1), 
    "time_id" : NumberInt(222), 
    "average_score" : NumberInt(8), 
    "count_editor_choice" : NumberInt(0)
}

game_dimension:
{ 
    "_id" : ObjectId("5ab703dcfc08b4855d3c0666"), 
    "game_id" : NumberInt(1), 
    "title" : "#IDARB", 
    "genre" : "Party", 
    "platform" : "Xbox One"
}

I wish to find this:
 Which platform had the most editor choice=1?

For this, i am using the query as follows:
db['fact '].aggregate([

{ 
            "$match" : {
                "editors_choice" : NumberLong(1)
            }
        }, 

{ "$lookup": {
    "localField": "game_id",
    "from": "game_dimension",
    "foreignField": "game_id",
    "as": "data"
} } ,

{$unwind: '$data'},
 {
   $group:
    { 
      _id: '$data.platform',
       "count(editors_choice)": 
      {
        $sum: 1
        }
      }
   },
   { 
            "$project" : {

                "platform" : "$data.platform", 
                "COUNT(editors_choice)" : "$count(editors_choice)"
            } }
])

-it显示0个文件。我对mongo很天真,对这个查询的一点帮助会清除我的很多疑问(并且如果可能的话也会加以解释)。

- 我正在努力做分组,并使用2个集合找到按组分组的平均值。提前谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了答案,这是:

收藏品:

db['fact '].aggregate([

{ 
            "$match" : {
                "count_editor_choice" : NumberLong(1)
            }
        }, 

{ "$lookup": {
    "localField": "game_id",
    "from": "game_dimension",
    "foreignField": "game_id",
    "as": "data"
} } ,

{$unwind: '$data'},
 {
   $group:
    { 
      _id: '$data.platform',
       "count(count_editor_choice)": 
      {
        $sum: 1
        }
      }
   },
   { 
            "$project" : {

                "platform" : "$data.platform", 
                "COUNT(count_editor_choice)" : "$count(count_editor_choice)"
            } }
])

正确的代码:

stereoRectify()