2013-02-03 14 views
5

コレクションがこのように見える場合、コレクション内のコメントをどのように取得するのですか。 (投稿当たりの総コメント数ではなく、コレクションの総数)コレクション内のサブ文書の合計を取得する

{ 
    _id: 1, 
    post: 'content', 
    comments: [ 
     { 
      name: '', 
      comment: '' 
     } 
    ] 
} 

私は3つのコメントを投稿し、5つのコメントを投稿しています。あなたはそのためのaggregation frameworkaggregate方法を使用することができます8.

答えて

12

あなたはaggregation frameworkを使用することができます。


ポストの数が多い場合は とは、 コメントの数を追跡するために、より効率的かもしれませんコメントしています。いつでもコメントが追加されると、カウンターが増えます。例:再び集約フレームワークを使用して

// Insert a comment 
> comment = { name: 'JohnDoe', comment: 'FooBar' } 
> db.prabir.update(
    { post: "A" }, 
    { 
     $push: { comments: comment }, 
     $inc: { numComments: 1 } 
    } 
) 

> db.prabir.aggregate(
    { $project : { _id: 0, numComments: 1 }}, 
    { $group: { 
     _id: '', 
     count: { $sum: "$numComments" } 
    } 
}) 
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 } 
+0

私はMongoDBのために新たなんです。単純なカウントを取得するためのコードは...恐ろしいです。 – otocan

8

結果は次のようになります。

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 } 

関連する問題