2016-06-29 7 views
3

私は、次のスキーマがあります。ATTRを使用して(他の期間もよい)関連集団の属性によってフィルタリングされた関連集計の集計で集計(トップ20のように)をソートする方法は?

var postSchema = new Schema({ 
    autor:    {type: Schema.Types.ObjectId, ref: 'user', required: true}, 
    texto:    {type: String}, 
    likes:    [{type: Schema.Types.ObjectId, ref: 'like'}], 

}); 

var likeSchema = new Schema({ 
    user:  {type: Schema.Types.ObjectId, ref: 'user', required: true}, 
    post:  {type: Schema.Types.ObjectId, ref: 'post', required: true}, 
    _created_at:{type: Date}, 
}); 

私は関係の数によってソートされたすべてのコレクションからのドキュメント「ポスト」が「好き」する最後の24時間以内に作成されました'_created_at'

F.I. 「過去24時間で最も好評を得た投稿」

私は、集約を使用するのは良いアイデアだと聞いたことがありますが、私は経験が不足していて、どのパイプラインを使うべきか分かりません。ポストIDは、あなたのために十分である場合

答えて

2

は、使用することができます:あなたは完全なポストを取得する必要がある場合は、しかし、

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

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 } 
]) 

は、これは、このようなリストを返します。同じクエリであれば、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/

これが役に立ちます。

乾杯!