如何按相关集合属性过滤的相关集合计数对集合(如前20个)进行排序?

时间:2016-06-29 23:49:12

标签: mongodb mongoose

我有以下架构:

1. For each label L of my labels 

   1.1 For each other user U in the app

       1.1.1 For each UL of that user's labels

          1.1.1.1 Check if L = UL (check if my current label equals that user's current label)

我想要收集所有文件' post'按关系数排序'喜欢'使用attr' _created_at'在过去24小时内(可能是其他时段)创建的。

F.I。 "过去24小时内收到最多喜欢的帖子"

我听说使用聚合是一个好主意,但我缺乏经验,并且不知道我应该选择什么样的管道。

1 个答案:

答案 0 :(得分:3)

如果帖子ID足够,您可以使用:

db.like.aggregate([
    //filter the likes creation dates as you need
    { $match  : { _created_at: { $gte: ISODate("2000-01-01T00:00:00.000Z"), $lt: ISODate("2020-12-31T00:00:00.000Z") } } },
    //group by post ID and count them
    { $group  : { _id: "$post", count: {$sum: 1} } },
    //sort by count, descending
    { $sort   : { count : -1 } },
    //limit the results in 20 maximum (if you need only the top 20)
    { $limit  : 20 }
])

这将返回如下列表:

[{
    "_id" : ObjectId("5774826af4a48761f2ff0da1"),
    "count" : 5
}, ...]

但是,如果您需要在同一个查询中获取完整的帖子,则需要MongoDB v.3.2(在此之前$ lookup不可用)。查询将是:

db.like.aggregate([
    //filter the likes creation dates as you need
    { $match  : { _created_at: { $gte: ISODate("2000-01-01T00:00:00.000Z"), $lt: ISODate("2020-12-31T00:00:00.000Z") } } },
    //group by post ID and count them
    { $group  : { _id: "$post", count: {$sum: 1} } },
    //sort by count, descending
    { $sort   : { count : -1 } },
    //limit the results in 20 maximum (if you need only the top 20)
    { $limit  : 20 },
    //bring the complete post from the related collection
    { $lookup : { from: "post", localField: "_id", foreignField: "_id", as: "post" } },
    //deconstructs the array created by lookup to a single object
    { $unwind : "$post" },
    //remove the ID and include on the complete post and count (this step is optional)
    { $project: { _id: 0, post: true, count: true } }
])

这将返回如下列表:

[{
    "count" : 5,
    "post" : {
        "_id" : ObjectId("5774826af4a48761f2ff0da1"),
        "autor" : ObjectId("577480bcf4a48761f2ff0d92"),
        "texto" : "texto06",
        "likes" : [
            ObjectId("5774882df4a48761f2ff0db9"),
            ObjectId("5774882df4a48761f2ff0dba"),
            ObjectId("5774882df4a48761f2ff0dbb"),
            ObjectId("5774882df4a48761f2ff0dbc"),
            ObjectId("5774882df4a48761f2ff0dbd")
        ]
    }
}, ...]

参考文献:

https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

https://docs.mongodb.com/manual/reference/method/db.collection.count/

希望这有帮助!

干杯!