【问题标题】:Mongo Distinct Count and WhereMongo 不同的计数和位置
【发布时间】:2016-05-09 23:38:59
【问题描述】:

我需要有关在 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 范围内为我提供 CountUnique Users,其中 类型 '资产搜索'

我可以在 SQL 中相对轻松地做到这一点,但 mongo 感觉更复杂。这里的一些专家可以帮助我吗?

【问题讨论】:

  • 不,只是我懒我现在更新它

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以通过多种方式解决此问题。第一种是使用聚合框架,它使用 $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);
});

【讨论】:

    【解决方案2】:
    User.find()
          .and([{'Type': 'Asset Search'},
                   $and: [
                           {'Timestamp': {$gt: date1}},
                           {'Timestamp': {$lt: date2}}
                         ]
          .count()
          .exec(function (err, userCount) {
             //do stuff
          })
    

    如果您想要两个日期之间的范围,您可能必须在 and 中添加第二个和条件。目前,通过此查询,您将获得时间戳大于 req.params.date 的所有用户的计数,然后键入“资产搜索”。还有你的时间戳字段真的是一个时间戳数组吗?

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

    【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多