棘手的Mongoose聚合查询

时间:2016-02-20 19:43:44

标签: node.js mongodb mongoose

给出了以下模式:

LogSchema {
    ...
    likes: Number,
    author: User,
    created_at: Date
    ...
}

以下查询似乎非常棘手:

获取对所有今天创建的日志最喜欢的前X用户。

结果应如下所示:

  • 用户x:1000喜欢
  • 用户y:558喜欢

我不知道如何攻击它。我知道,我可以使用一些聚合,但是应该如何在这里完成,因为喜欢以某种方式绑定到用户。

1 个答案:

答案 0 :(得分:2)

以下是在Mongo Shell下使用测试数据

的命令.aggregate()的示例
{ "_id" : ObjectId("56c912a1ebf94ca549e4ab8f"), "likes" : 123, "author" : "x", "created_at" : ISODate("2016-02-21T01:28:01.549Z") }
{ "_id" : ObjectId("56c912aaebf94ca549e4ab90"), "likes" : 120, "author" : "x", "created_at" : ISODate("2016-02-21T01:28:10.116Z") }
{ "_id" : ObjectId("56c912b4ebf94ca549e4ab91"), "likes" : 12, "author" : "y", "created_at" : ISODate("2016-02-21T01:28:20.996Z") }
{ "_id" : ObjectId("56c912bbebf94ca549e4ab92"), "likes" : 22, "author" : "y", "created_at" : ISODate("2016-02-21T01:28:27.644Z") }

命令

> var d = new Date();
> d.setHours(0, 0, 0); // set to the first second of today, used for query today logs
> db.log.aggregate([
     // query today logs by `create_at`
     {$match: {created_at: {$gt: d}}}, 
     // group by author and sum the `likes`
     {$group: {_id: '$author', likes: {$sum: '$likes'}}}
  ]).map(function(val) {
     // map the field per request
     return {[val._id]: val.likes}
  });

结果

[ { "y" : 34 }, { "x" : 243 } ]

使用猫鼬aggregate,请尝试

var p = Log.aggregate([
           // query today logs by `create_at`
           {$match: {created_at: {$gt: d}}}, 
           // group by author and sum the `likes`
           {$group: {_id: '$author', likes: {$sum: '$likes'}}}
        ]).exec();
p.then(function(vals){
        return vals.map(function(val) {
           return {[val._id]: val.likes};
        });
});