結果は次のようになります。
db.test.aggregate(
// Only include docs with at least one comment.
{$match: {'comments.0': {$exists: true}}},
// Duplicate the documents, 1 per comments array entry
{$unwind: '$comments'},
// Group all docs together and count the number of unwound docs,
// which will be the same as the number of comments.
{$group: {_id: null, count: {$sum: 1}}}
);
UPDATEのMongoDB 2.6のよう
を行うためのより効率的な方法がありますこれは$size
アグリゲーション演算子を使用して、各文書のコメント数を直接取得します。
これは、(一時的に)各コメントに個別の文書を作成し、文書ごとに
count
インクリメント一言で言えば
> db.prabir.aggregate(
{ $unwind : "$comments" },
{ $group: {
_id: '',
count: { $sum: 1 }
}
})
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 }
:
私はMongoDBのために新たなんです。単純なカウントを取得するためのコードは...恐ろしいです。 – otocan