2013-02-03 21 views
5

Koleksiyonum böyle görünüyorsa koleksiyondaki toplam yorumları nasıl alırım. (Toplama sonrası ancak toplamda başına değil toplam yorumlar.)Koleksiyondaki tüm alt belgeleri al

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

Ben 5 yorumlarla 3 yorumlarla sonrası A ve sonrası B varsa. Bunun için aggregation framework ait aggregate yöntemi kullanabilirsiniz 8.

cevap

12

Sen aggregation framework kullanabilirsiniz.


mesajların sayısı çoksa ve yorum sayısının takip etmek için daha verimli olabilir yorumlar. Bir yorum eklendiğinde, bir sayaç da artar. Örnek: Yeniden toplama çerçevesini kullanma

// 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

Ben mongodb yeniyim. Basit bir sayı elde etmek için bu kod ... korkunçtur. – otocan

8

sonucu olmalıdır:

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

GÜNCELLEME MongoDB 2.6 itibariyle

yapmak için daha etkili bir yol var Bu, her bir belgedeki yorum sayısını doğrudan almak için $size toplama operatörünü kullanarak:

Bu (geçici olarak) her yorum için ayrı bir doküman oluşturur ve ardından her bir belge için count artırır Özetle

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

:

İlgili konular