【问题标题】:group on mongodb filtering by any field按任何字段过滤mongodb组
【发布时间】:2015-07-23 09:37:30
【问题描述】:

我正在尝试对 mongodb(使用 mongoose)进行组查询,通过除组条件之外的任何其他不同字段进行过滤。我现在有这个:

usersDB.aggregate().group (
    {_id: '$residence', total: { $sum: 1 } } 
).exec(function (err, result) {
        if(err) res.send(err);
        else res.send(result);
});

它有效......它向我展示了例如:

[{"_id":"Javea","total":40},{"_id":"Benissa","total":28},{"_id":"Calpe","total":41},{"_id":"Teulada","total":14}]

但是现在,我想做的也是按上次访问日期过滤(last_visit 是 UsersDB 的其他字段)。我试过这个:

    usersDB.find({$and:[{last_visit:{$lt:date}}, {last_visit:{$gt:date.setMonth(3)}}]}).aggregate().group(
    {_id: '$residence', total: { $sum: 1 } }).exec(
    function (err, result) {
        if(err) res.send(err);
        else res.send(result);
    });

当然......它不起作用!

有什么建议吗?

【问题讨论】:

    标签: node.js mongodb express mongoose mongodb-query


    【解决方案1】:

    您需要使用$match 运算符阶段在聚合管道中进行过滤:

    var start = date,  end = date;
    end.setMonth(3);
    var query = { "last_visit": { "$lt": end, "$gt": start } };
    
    usersDB.aggregate()
           .match(query)
           .group({"_id": "$residence", "total": { "$sum": 1 } })
           .exec(function (err, result) {
                if(err) res.send(err);
                else res.send(result);
           });
    

    【讨论】:

      【解决方案2】:

      在 mongo shell 中,它看起来像:

      db.users.aggregate([
      { $match : { $and [{last_visit:{$lt:date}}, {last_visit:{$gt:date.setMonth(3)}}]}},
      { $group : { _id: '$residence', total: { $sum: 1 } }}
      ]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-19
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        相关资源
        最近更新 更多