MongoDB $ group + $ project +每周平均

时间:2018-11-01 09:57:31

标签: mongodb mongodb-query

我正在尝试获取Mongo每周某些商店的平均点播费用,但这不起作用。你能帮我吗?

db.collection.aggregate(
[
    {$match:{storeId:{$in:[
ObjectId("e069d1b76557685b9e235v"),ObjectId("e069d1b76557685b9t7j8n"),
ObjectId("e069d1b76557685b9e2fg6"),ObjectId("e069d1b76557685b9p56r2") 
]}}},
{$group:{_id:"$storeId", week: { date: new Date("$createdAt")  }, totalPoints: {$sum: "$points"}, averagePoints: {$avg: "$points"}} },
    {$sort: {totalPoints:-1}}
])

它不起作用。但是,如果我删除一周的一部分,则代码可以正常工作,但得出错误的平均值

db.collection.aggregate(
[
    {$match:{storeId:{$in:[
ObjectId("e069d1b76557685b9e235v"),ObjectId("e069d1b76557685b9t7j8n"),
ObjectId("e069d1b76557685b9e2fg6"),ObjectId("e069d1b76557685b9p56r2") 
]}}},
{$group:{_id:"$storeId", totalPoints: {$sum: "$points"}, averagePoints: {$avg: "$points"}} },
    {$sort: {totalPoints:-1}}
])

1 个答案:

答案 0 :(得分:1)

% progname datafile [...skipping to the end...] 7484,4[11,5,14,2,6,7,8,1,0] budget : 7484 hotelType: 4 events : [11,5,14,2,6,7,8,1,0] [ 11 5 14 2 6 7 8 1 0 ] budgets : [9020,7805,7075,7679,6356,6874,4715,4784,4321,6469,4838,4103,5904,5775,7070,4605,7484] hotelTypes : [4,5,5,4,3,5,4,5,3,5,4,3,5,3,4,3,4] event_lists: [[2,0,5,14,10,4,3,13,1] [13,3,12,12,0,9,7,10,6,1] [3,2,4,9,7,0,1,5,6,14] [0,4,14,1,3,12,5,10] [7,3] [14,0,4,10,9,3] [9] [11] [5,3,8,9] [7,6,6,14,12,5,2] [1,2] [14] [5,4,6] [10,14,14,8,7,3,4] [1,4,6,11,13,3,2,5,14] [6,10,1,8,7,3,3] [11,5,14,2,6,7,8,1,0]] 周内,您可以使用mongo的groupBy函数并在$week操作中添加开始日期。

$match