我需要有关在 Mongo 中运行 Distinct、Count 和 Where 查询的帮助。 集合名为 'trackedevents'
{
Type: 'Asset Search',
User: 'ABC'
Timestamp: '26/01/2015'
},
{
Type: 'Asset Search',
User: 'DEF'
Timestamp : '27/01/2015'
}
我需要帮助的是让 mongo 在某个 Timestamp 范围内给我 Count 的 Unique Users ,其中 类型是' Assets 搜索'
我可以在 SQL 中相对容易地做到这一点,但 mongo 感觉更复杂。这里的一些专家可以帮助我解决这个问题吗。
最佳答案
您可以通过多种方式解决这个问题。第一种是使用聚合框架,它使用 $match
和 $group
查询和分组文档的流水线步骤
用户字段然后获取计数:
var pipeline = [
{
"$match": {
"Type": "Asset Search",
"Timestamp": { "$gte": start, "$lte": end }
}
},
{
"$group": {
"_id": "$User",
"count": { "$sum": 1 }
}
}
];
TrackedEvent.aggregate(pipeline, function(err, result){
if (err) { /* Handle error */ }
console.log(result);
})
另一种方法是使用 distinct()
的组合 和 count()
方法
var query = {
"Type": "Asset Search",
"Timestamp": { "$gte": start, "$lte": end }
};
TrackedEvent.distinct('User', query).count().exec(function (err, count) {
console.log('The number of unique users is: %d', count);
});
关于javascript - Mongodb 非重复计数和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131908/