は、使用することができます:あなたは完全なポストを取得する必要がある場合は、しかし、
[{
"_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/
これが役に立ちます。
乾杯!