我有一个 mongoDB 数据库,其中包含由不同用户创建的对象。现在为了跟踪用户保留率和活跃用户,我想每周一次了解有多少不同的用户创建了新对象。
例如,假设对象是“注释”。如何有效地统计上周有多少不同的用户创建了注释?
注意:
{
"user_id" : "..."
"note" : "..."
"date" : "..."
}
我使用 Mongoose 和 NodeJS。
最佳答案
假设集合附加到名为 Note
的模型,并且 "date"
中的数据实际上是有效的 Date
对象,则您本质上是查询给定日期和聚合之间的数据:
// Work out days for start of tomorrow and one week before
const oneDay = 1000 * 60 * 60 * 24,
oneWeek = oneDay * 7;
const d = Date.now();
const lastDay = d - ( d % oneDay ) + oneDay;
const firstDay = lastDay - oneWeek;
// Run the aggregation
Note.aggregate([
// $match is a query to select the week
{ "$match": { "date": { "$gte": new Date(firstday), "$lt": new Date(lastDay) } },
// $group on the distinct users
{ "$group": { "_id": "$user_id" } },
// $group to count the total
{ "$group": { "_id": null, "count": { "$sum": 1 } } }
],function(err, results) {
// results in here
})
$match
是一个“查询”,就像任何其他 MongoDB 查询语句一样。您使用$gte
和 $lt
运算符来表示可以落在其间的值的“范围”。这实际上是一种编写 AND 条件的简写方式,无需明确说明该术语。
下一阶段是$group
我们通过应用分组键(_id
)来将“user_id
”字段数据“聚合”为“不同”值。分组键的输出始终是唯一的。
最后一个阶段是另一个$group
,这次分组键为 null
而不是使用当前字段值。这意味着“将所有内容分组”,因此我们最终得到应用 $sum
的单行。对 1
的值进行运算以实现“计数”。
这就是聚合“管道”的工作方式,每个“阶段”都会流入下一个“阶段”。所以“Query”->“Aggregate Distinct”->“Aggregate Total”就是这种模式,其中最重要的是要记住,每个阶段只能看到上一个阶段输出的数据的 View 。
一旦掌握了这些概念,这就很容易了。
关于javascript - 计算上周的活跃用户数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44735667/