ユーザーが好きだったコンテンツの合計を取得しようとしました、共有またはコメント。MongoDbは3つのフィールドの数/合計を集計します
私のコンテンツモデルは以下の構造を持っています。
Content = {
_id: ObjectId(),
author: ObjectId(),
value: <string of post content>
tags: [<trings>],
likes: [array of user ids],
shares: [array of user ids],
comments: [{
ContentId(of the same schema),
User Id
}]
}
さて、IDは、コンテンツの文書を超える集約 と、このような結果を取得したいです。コンテンツがある時はいつでも
{
likes: 20,
shares: 10,
comments: 5
}
Soは、短期では、ユーザIDが好き配列である は、 好きは株式とコメントのための同じ1
インクリメントします。
これが集約フレームワークで可能かどうかはわかりません。 私はそう思わないかもしれませんが、多分mongodbの達人がもっとよく知っているかもしれません。
クイック編集。部分的に提出された最初の投稿に基づいて、私はこれを作った。 は今、動作しているようですが、それはあまりにも簡単なようですので、イム必ず落とし穴のいくつかの並べ替えは、不足していることイムがある:)
db.getCollection('contents').aggregate([
{$facet: {
"likes": [
{$match: {likes: ObjectId("596537d6b63edc2318ee9f0c")} },
{$group: {
_id : "$likes",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
],
"shares": [
{$match: {shares: ObjectId("596537d6b63edc2318ee9f0c")} },
{$group: {
_id : "$shares",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
],
"posts": [
{$match: {$and: [
{user: ObjectId("596537d6b63edc2318ee9f0c")},
{parent: {$exists: false} }
]} },
{$group: {
_id : "$_id",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
]
}
}]);
することができます上記のコードで間違った場所に何か?