蒙戈不同的计数和地点

Mongo Distinct Count and Where

本文关键字:      更新时间:2023-09-26

我需要帮助在Mongo中运行Distinct,Count和Where查询。集合称为"跟踪事件"

{
    Type: 'Asset Search',
    User: 'ABC'
    Timestamp: '26/01/2015'
},
{
    Type: 'Asset Search',
    User: 'DEF'
    Timestamp : '27/01/2015'
}

我需要帮助的是让 mongo 在某个时间戳范围内给我一个唯一用户计数其中类型"资产搜索"

我可以在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);
});
User.find()
      .and([{'Type': 'Asset Search'},
               $and: [
                       {'Timestamp': {$gt: date1}},
                       {'Timestamp': {$lt: date2}}
                     ]
      .count()
      .exec(function (err, userCount) {
         //do stuff
      })

如果您想要 2 个日期之间的范围,您可能需要在 and 中添加第二个和条件。目前使用此查询,您将获取时间戳大于 req.params.date 的所有用户的计数,并键入"资产搜索"。另外,您的时间戳字段真的是时间戳数组吗?

现在编辑它就像你希望的那样

相关文章:
  • 没有找到相关文章